﻿/// <reference path="/content/js/jquery.docs.js" />

// Load jQuery from Google
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");

google.setOnLoadCallback(function () {

    $('.top-row select').change(function () {

        $('#choose-subscription').submit();

    });

    $('#slider-noback').codaSlider({
        crossLinking: false,
        dynamicArrows: false
    });

    $('.button button').mousedown(function () {
        $(this).parent().addClass('button-toggle');
    });

    $('.button button').mouseup(function () {
        $(this).parent().removeClass('button-toggle');
    });


    $(document).ready(function () {
        $('#cssdropdown li.headlink').hover(
			function () { $('ul', this).css('display', 'block'); },
			function () { $('ul', this).css('display', 'none'); });
    });

    // Add watermarks to inputs
    $('input').each(function () {
        var input = $(this);
        var watermark = input.attr('watermark');
        if (watermark) {
            input.watermark(watermark, { className: 'watermark' });
        }
    });

    $('textarea').each(function () {
        var input = $(this);
        var watermark = input.attr('watermark');
        if (watermark) {
            input.watermark(watermark, { className: 'watermark' });
        }
    });

    tb_init('a.thickbox');

    $("#btnWatchdogSignUp").click(function () {
        tb_show("Watchdog Online Brand Protection", "/home/signupwatchdog?width=850&height=310");
    });

    // Load Grid
    watchdog.table.init('/table/data');



    // Grid Error Handler
    dhtmlxError.catchError("LoadXML", function () {

    });

    watchdog.filter.init();

    // Input hints
    $(".jazz-hands input").focus(function () {
        showHint(this);
    });

    $(".jazz-hands select").focus(function () {
        showHint(this);
    });

    $(".jazz-hands textarea").focus(function () {
        showHint(this);
    });

    $(".jazz-hands input").blur(function () {
        $(this).parent().find(".hint").remove();
    });

    $(".jazz-hands select").blur(function () {
        $(this).parent().find(".hint").remove();
    });

    $(".jazz-hands textarea").blur(function () {
        $(this).parent().find(".hint").remove();
    });

    $(".jazz-hands label").mouseover(function () {
        showHint(this);
    });

    $(".jazz-hands label").mouseout(function () {
        //$(".hint").hide();
        $(this).parent().find(".hint").remove();
    });

    //Set custom configurations
    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 100, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $("ul#topnav li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
    $("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations

    $('#gMap').click(function () {
        watchdog.map.create()
    });

    $('#tagCloud').click(function () {

        if (grid.destructor) grid.destructor();

        $('#results').css('border-top', 'solid 1px #ccc')
					 .css('height', 'auto'); ;

        $.get('/table/tagcloud', function (data) {
            $('#results').html(data);
        });

        $('#tagCloud').hide();
        $('#gMap').show();
        $('#tableLink').show();

        return false;

    });

    $('#tableLink').click(function () {

        createGrid();

        return false;

    });

    var message = $(".message");

    if (message.length > 0) {
        setTimeout(hideMessage, 5000);
    }

});

// Main Watchdog namespace
var watchdog = {};

// Core watchdog functionality
watchdog.core = function () {

    return {

        urlEncode: function (input) {
            /// <summary>
            /// Safely encodes a given input to a URL safe string
            ///</summary>    

            var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()"; 				// RFC2396 Mark characters

            var HEX = "0123456789ABCDEF";

            var encoded = "";

            for (var i = 0; i < input.length; i++) {

                var ch = input.charAt(i);

                if (SAFECHARS.indexOf(ch) != -1) {
                    encoded += ch;
                } else {
                    var charCode = ch.charCodeAt(0);
                    if (charCode > 255) {
                        encoded += "+";
                    } else {
                        encoded += "%";
                        encoded += HEX.charAt((charCode >> 4) & 0xF);
                        encoded += HEX.charAt(charCode & 0xF);
                    }
                }
            }

            return encoded;
        }
    }

} ();

// Table Code
watchdog.table = function () {

    // The URL to get the table data from
    var url;

    return {
        init: function (value) {
            /// <summary>
            /// Initilizes the DHTMLX table control
            ///</summary>   

            url = value;

            var results = $("#results");

            if (results.length > 0) {

                results.empty();
                $('#results').css('border-top', 'none');

                grid = new dhtmlXGridObject('results');
                grid.setImagePath("/content/images/dhtmlx/");
                grid.setSkin("light");

                if (window.doOnRowSelected) {
                    grid.attachEvent("onRowSelect", doOnRowSelected);
                }

                var url = $('#table-url');

                if (url.length > 0) {
                    url = $('#table-url').val();
                    grid.init();
                    grid.enableSmartRendering(true, 100);
                    grid.setAwaitedRowHeight(22);
                } else {
                    url = '/table/data';
                    grid.init();
                }

                grid.loadXML(url);
                results.css("display", "block");

                if (window.dataProcessor) {
                    var dp = new dataProcessor('/setting/update');

                    dp.init(grid);

                    if (window.initDp) window.initDp(dp);
                }

            }

            $('#tagCloud').show();
            $('#tableLink').hide();

            $(window).unload(function () {
                $("#result").hide();
            });

        },

        reload: function (newUrl) {
            /// <summary>
            /// Reloads the DHTMLX table with a new XML data stream
            ///</summary>      
            grid.loadXML(newUrl);
        },

        reset: function () {
            /// <summary>
            /// Reloads the DHTMLX table with the original XML data
            ///</summary>      
            grid.loadXML(url);
        }
    }

} ();


// Table Filter Code
watchdog.filter = function () {

    // URL that runs the filter
    var url;

    function processKeydown(event) {
        /// <summary>
        /// Processes keypresses in the filter text box
        ///</summary>         

        // Remove filter on ESC
        if (event.keyCode == '27') {
            $("#filter").fadeOut("normal");
        }

        // Run filter on Enter
        if (event.keyCode == '13') {

            performFilter($("#filter-text").val());
            return false;
        }
    }

    return {

        init: function (value) {
            /// <summary>
            /// Initilizes the filter on a DHTMLX table
            ///</summary>     

            // Set filter URL
            url = value;

            // Assign events
            $('#show-filter').click(watchdog.filter.show);

            // Assign hotkeys
            $(document).keydown(watchdog.filter.hotkey);

            // Handle keypresses
            $("#filter-text").keydown(processKeydown);

            $("#filter-button").click(function () {
                performFilter($("#filter-text").val());
            });

            $("#filter-clear").click(function () {
                watchdog.filter.remove();
            });

            $("#remove-filter-link").click(function () {
                watchdog.filter.remove();
            });
        },

        show: function () {
            /// <summary>
            /// Displays the quick filter window
            ///</summary>     
            $("#filter").show("fast", function () {
                var txt = $("#filter-text");
                if (txt.val() == "") txt.val("type a search term and press enter");
                txt.select();
                txt.focus();
            });
        },

        remove: function () {
            /// <summary>
            /// Hides the quick filter window
            ///</summary>       
            $("#filter").fadeOut("normal");
        },

        hotkey: function (event) {
            /// <summary>
            /// Processes hotkeys for the filter
            ///</summary>       

            // assign hot-key ('F')            
            if (event.keyCode == '70') {
                if ($("#results").is(':visible')) {
                    watchdog.filter.show();
                    return false;
                }
            }

            // assign hot-key ESC to remove filter
            if (event.keyCode == '27') {
                if ($("#filter-message").is(':visible')) {
                    watchdog.filter.remove();
                    return false;
                }
            }
        },

        perform: function (filter) {
            /// <summary>
            /// Performs a filter on the DHTMLX table by reloading
            /// the table data from the filter URL
            ///</summary>            
            var filterUrl = url + '?q=' + watchdog.core.urlEncode(url);
            watchdog.table.reload(filterUrl);
        },

        clear: function () {
            /// <summary>
            /// Clears the current filter from the table.
            ///</summary>  
            watchdog.filter.remove();
            watchdog.table.reset();
        }

    }

} ();

// Google Map Code
watchdog.map = function () {

    // Private variables
    var map = null;                 // The Google Map
    var markers = [];               // Any points
    var markerCluster = null;       // The clusters   
    var reloadMarkerTimer = null;   // Drag-drop event timer
    var reloadingMarkers = false;   // Reloading flag
    var lastPoint;                  // Last lat/lng
    var tag = '';                   // The asset tag to display
    var mapUrl = '';                // The map URL

    var infowindow = new google.maps.InfoWindow({ content: '' });

    function getHeatMapObject(colorScheme) {
        /// <summary>
        /// Gets the heat map object to overlay on the map..
        ///</summary>
        var heatMapOptions = {
            getTileUrl: function (tile, zoom) {
                var url = '/pages/tile.aspx?colorScheme=' + colorScheme
                        + '&zoom=' + zoom
                        + '&x=' + tile.x
                        + '&y=' + tile.y
                        + '&rand=' + Math.random();

                return url;
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: true,
            releaseTile: function (tile, zoom) {
                //Called when a tile is out of view
            },
            name: colorScheme + "Heat Map"
        };
        return new google.maps.ImageMapType(heatMapOptions);
    }

    function changeColorScheme(control) {
        /// <summary>
        /// Changes the colour scheme of the heat map
        ///</summary>
        map.overlayMapTypes.removeAt(0);
        if (colorSchemeArray[control.value] == null) {
            //Get a new one
            colorSchemeArray[control.value] = getHeatMapObject(control.value);
        }
        //Now set it
        map.overlayMapTypes.insertAt(0, colorSchemeArray[control.value]);
    }

    function distanceThreshold(zoom) {
        /// <summary>
        /// Determines the distance in km that a map can move before it's contents
        /// are refreshed from the server.
        ///</summary>
        var distance;
        switch (zoom) {
            case 0:     // Out in space
                distance = 100;
                break;
            case 1:
                distance = 100;
                break;
            case 2:
                distance = 100;
                break;
            case 3:
                distance = 100;
                break;
            case 4:
                distance = 10;
                break;
            case 5:
                distance = 5;
                break;
            case 6:
                distance = 4;
                break;
            case 7:
                distance = 3;
                break;
            case 8:
                distance = 2;
                break;
            case 9:
                distance = 1;
                break;
            case 10:
                distance = 0.75;
                break;
            case 11:
                distance = 0.75;
                break;
            case 12:
                distance = 0.5;
                break;
            case 13:
                distance = 0.5;
                break;
            case 14:
                distance = 0.25;
                break;
            case 15:
                distance = 0.25;
                break;
            case 16:
                distance = 0.25;
                break;
            case 17:
                distance = 0.25;
                break;
            case 18:     // In your face
                distance = 0.1;
                break;
            default:
                distance = 0.1;
                break;
        }

        return distance;
    };

    function markerThreshold(zoom) {
        /// <summary>
        /// Determines the number of maximum number of markers to load for a
        /// given zoom level.
        ///</summary>
        var count;
        switch (zoom) {
            case 0:     // Out in space
                count = 2000;
                break;
            case 1:
                count = 2000;
                break;
            case 2:
                count = 2000;
                break;
            case 3:
                count = 2000;
                break;
            case 4:
                count = 2000;
                break;
            case 5:
                count = 2000;
                break;
            case 6:
                count = 2000;
                break;
            case 7:
                count = 2000;
                break;
            case 8:
                count = 1500;
                break;
            case 9:
                count = 1000;
                break;
            case 10:
                count = 1000;
                break;
            case 11:
                count = 1000;
                break;
            case 12:
                count = 1000;
                break;
            case 13:
                count = 750;
                break;
            case 14:
                count = 500;
                break;
            case 15:
                count = 300;
                break;
            case 16:
                count = 200;
                break;
            case 17:
                count = 175;
                break;
            case 18:     // In your face
                count = 150;
                break;
            default:
                count = 100;
                break;
        }

        return count;
    };

    // Public methods
    return {

        create: function (url) {
            /// <summary>Creates a Google map</summary>

            if (window.grid) {
                if (grid.destructor) grid.destructor();
            }

            $('#map').css('height', '580px')
				     .css('border', 'solid 1px #ccc');

            mapUrl = url;

            watchdog.map.draw();

            if (url) watchdog.map.populate(mapUrl);

            $('#map-fullscreen-link').click(function () {
                return watchdog.map.fullscreen();
            });

            $('#map-normal-link').click(function () {
                return watchdog.map.normalScreen();
            });

            $('.btnApply').click(function () {
                var from = $('#map-from').val();
                var to = $('#map-to').val();

                watchdog.map.filter(mapUrl, from, to);
            });

            return false;
        },

        draw: function () {

            var lat = 54.584797;
            if ($('#map-lat').length > 0) lat = $('#map-lat').val();

            var lng = -2.219238;
            if ($('#map-lng').length > 0) lng = $('#map-lng').val();

            var zoom = 6;
            if ($('#map-zoom').length > 0) zoom = parseInt($('#map-zoom').val());


            var latlng = new google.maps.LatLng(lat, lng);
            var myOptions = {
                zoom: zoom,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(document.getElementById("map"), myOptions);

            if (mapUrl) {
                google.maps.event.addListener(map, 'center_changed', function () {

                    clearTimeout(reloadMarkerTimer);
                    reloadMarkerTimer = setTimeout('watchdog.map.reload()', 3000);
                    if (!reloadingMarkers) {
                        watchdog.map.setStatus('Waiting...');
                    }

                });
            }

        },

        populate: function (url) {

            var latLng = map.getCenter();
            var zoom = markerThreshold(map.getZoom());

            var toDownload = url + '?lat=' + latLng.lat() + '&lng=' + latLng.lng() + '&maximum=' + zoom;
            if (tag != '') toDownload += '&tag=' + tag;

            $.getJSON(toDownload, function (data) {

                watchdog.map.clearStart();

                for (var x in data) {

                    var lat = data[x].lat;
                    var lng = data[x].lng;
                    var id = data[x].id;
                    var url = data[x].popupUrl;
                    var title = data[x].title;
                    var weight = data[x].weight;

                    var marker = watchdog.map.marker(id, lat, lng, title, url, weight);

                    if (marker) { // only add new markers
                        var found = false;
                        for (var i = 0; i < markers.length; i++) {
                            if (markers[i].id == marker.id) found = true;
                        }
                        if (!found) {
                            markers.push(marker);
                        } else {
                            marker.setMap(null);
                        }
                    }
                }

                if (!markerCluster) {
                    var mcOptions = { gridSize: 60, maxZoom: 14 };

                    markerCluster = new MarkerClusterer(map, markers, mcOptions);
                } else {
                    markerCluster.clearMarkers();
                    markerCluster.addMarkers(markers)
                }

                reloadingMarkers = false;

                watchdog.map.setStatus('<strong>' + markers.length + '</strong> points.');
            });
        },

        clear: function () {

            if (markerCluster) {
                markerCluster.clearMarkers();
            }

            if (markers) {
                for (var i = 0; i < markers.length; i++) {
                    markers[i].setMap(null);
                }
                markers = new Array();
            }
        },

        clearStart: function () {

            while (markers.length > 20000) {
                markerCluster.removeMarker(markers[0]);
                markers[0].setMap(null);
                markers.splice(0, 1);
            };
        },

        reload: function (force) {

            if (!reloadingMarkers) {

                var latLng = map.getCenter();
                var currentPoint = new LatLon(latLng.lat(), latLng.lng());

                if (lastPoint) {
                    var distance = currentPoint.distanceTo(lastPoint);
                }
                else {
                    distance = 9999999;
                }
                var threshold = distanceThreshold(map.getZoom());

                if (force) distance = 9999999;

                if (distance > threshold) {
                    lastPoint = currentPoint;
                    reloadingMarkers = true;
                    watchdog.map.setStatus('<img src="/content/images/loader.gif"> Refreshing...');
                    watchdog.map.populate(mapUrl);
                } else {
                    watchdog.map.setStatus('Moved map.');
                }
            }
        },

        marker: function (id, lat, lng, title, url, weight) {

            var myLatlng = new google.maps.LatLng(lat, lng);

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: title,
                id: id,
                popupUrl: url
            });

            if (weight > 0) {
                marker.setIcon('/content/images/markers/lightblue' + weight + '.png');
            }

            google.maps.event.addListener(marker, 'click', function () {

                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'html',
                    success: function (data) {
                        infowindow.content = data;
                        infowindow.open(map, marker);
                    }
                });
            });

            return marker;
        },

        center: function (location) {
            map.setCenter(location);
            map.setZoom(13);
        },

        setStatus: function (html) {
            $('.map-status').html(html);
        },

        fullscreen: function () {

            var div = $('#map');
            div.css('position', 'absolute');
            div.css('top', '0');
            div.css('left', '0');
            div.css('height', '100%');
            div.css('width', '100%');
            div.css('margin', '0');

            var bar = $('.map-bar');
            bar.addClass('full-screen-bar');

            var date = $('.map-date');
            date.hide();

            $('#map-fullscreen-link').hide();
            $('#map-normal-link').show();

            google.maps.event.trigger(map, "resize");

            return false;
        },

        normalScreen: function () {

            var div = $('#map');
            div.css('position', 'relative');
            div.css('top', '0');
            div.css('left', '0');
            div.css('height', '580px');
            div.css('width', '910px');
            div.css('margin', '0 0 0 10px');

            var bar = $('.map-bar');
            bar.removeClass('full-screen-bar');

            var date = $('.map-date');
            date.show();

            $('#map-fullscreen-link').show();
            $('#map-normal-link').hide();

            google.maps.event.trigger(map, "resize");

            return false;
        },

        setTag: function (value) {
            tag = value;

            watchdog.map.clear();
            watchdog.map.reload(true);
        },

        heatmap: function () {

            //add the default overlaycc
            map.overlayMapTypes.insertAt(0, getHeatMapObject('classic'));
        },

        goto: function (url) {
            var center = map.getCenter();
            var zoom = map.getZoom();

            var navigateTo = url + '?lat=' + center.lat() + '&lng=' + center.lng() + '&zoom=' + zoom;

            window.top.location = navigateTo;
        },

        filter: function (url, from, to) {

            var center = map.getCenter();
            var zoom = map.getZoom();

            var navigateTo = '/postcode-asset-heat-map/map?lat=' + center.lat() + '&lng=' + center.lng() + '&zoom=' + zoom + '&from=' + from + '&to=' + to;

            window.top.location = navigateTo;
        }
    }
} ();

function hideMessage() {

    var message = $(".message").fadeOut("slow");

}

function showLocationMap(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);

    var myOptions = {
        zoom: 6,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);

    createMarker("id", lat, lng, "Item Location", "#");
}

function showHint(obj) {

    if ($(obj).attr("hint")) {

        var hint = $(obj).attr("hint");

        if ($(obj).parent().find("label.error").length == 0) {
            $(obj).parent().append("<label class='hint'>" + hint + "</label>");
        }

    }
}

function eXcell_thickbox(cell) {
    if (cell) {
        this.cell = cell;
        this.grid = this.cell.parentNode.grid;
    }
    this.edit = function () { }
    this.isDisabled = function () { return true; }
    this.setValue = function (val) {

        var parts = val.split("^");

        var claretPos = val.indexOf("^", 0);
        var text = val.substr(0, claretPos);
        var url = val.substr(claretPos + 1);

        this.setCValue('<a href="#" onclick="return tb_show(\'\', \'' + parts[1] + '\')" class="' + parts[2] + '">' + parts[0] + '</a>', val);
    }
}
eXcell_thickbox.prototype = new eXcell;

function eXcell_button(cell) {
    if (cell) {
        this.cell = cell;
        this.grid = this.cell.parentNode.grid;
    }
    this.edit = function () { }
    this.isDisabled = function () { return true; }
    this.setValue = function (val) {

        var claretPos = val.indexOf("^", 0);
        var text = val.substr(0, claretPos);
        var url = val.substr(claretPos + 1);

        this.setCValue("<span class='button strong small'><a href='" + url + "' >" + text + "</a></span>", val);
    }
}
eXcell_button.prototype = new eXcell;

function eXcell_linkHtml(cell) {
    if (cell) {
        this.cell = cell;
        this.grid = this.cell.parentNode.grid;
    }
    this.edit = function () { }
    this.isDisabled = function () { return true; }
    this.setValue = function (val) {
        this.setCValue(val, "");
    }
}
eXcell_linkHtml.prototype = new eXcell;

//On Hover Over
function megaHoverOver() {
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function ($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function () {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function () { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery);

    if ($(this).find(".row").length > 0) { //If row exists...

        var biggestRow = 0;

        $(this).find(".row").each(function () {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if (rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({ 'width': biggestRow }); //Set width
        $(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({ 'width': rowWidth }); //Set Width

    }
}
//On Hover Out
function megaHoverOut() {
    $(this).find(".sub").stop().hide();
}



function toggleCheckbox(checkbox) {
    var input = $(checkbox);
    if (input.is(':checked')) {
        input.removeAttr('checked');
    } else {
        input.attr('checked', 'checked');
    }
}

function createCalendar() {
    // Create calendars
    $('.calendar').datepicker({
        changeYear: true,
        yearRange: '1910:2020',
        dateFormat: 'dd/mm/yy',
        minDate: new Date(1890, 1 - 12, 1),
        showOn: 'button',
        buttonImageOnly: true,
        buttonImage: '/Content/Images/CalendarImage.png'
    });
}

