//--------------------------------------------------------------------------------------//
//                              SIDEBAR SLIDER FUNCTIONALITY                            //
//--------------------------------------------------------------------------------------//

$kpi = jQuery.noConflict();

$kpi(document).ready(function () {
    $kpi("#menu-toggle").click(function (e) {
        e.preventDefault();
        $kpi("#wrapper").toggleClass("toggled");
        $kpi("#menu-toggle").toggleClass("button-untoggled");
    });

    $kpi('.item li p .imgAccordionSlider').click(function () {
        //e.preventDefault();
        if ($kpi(this).closest("ul").css('max-height') == '25px') {
            //$kpi('.item').not(this).closest("ul").css('max-height', '20px');
            $kpi(this).closest("ul").css('max-height', '420px');
            $kpi(this).removeClass("glyphicon-menu-down");
            $kpi(this).addClass("glyphicon-menu-up");
        }
        else {
            $kpi(this).closest("ul").css('max-height', '25px');
            $kpi(this).removeClass("glyphicon-menu-up");
            $kpi(this).addClass("glyphicon-menu-down");
        }
    });
});

$kpi(document).ready(function () {
    $kpi('.scrollbar-inner').scrollbar();
    $kpi('.scrollbar-inner1').scrollbar();
});

$kpi(document).ready(function () {
    $kpi('.Tooltip').tooltipster({
        animation: 'grow',
        delay: 200,
        theme: 'tooltipster-default',
        touchDevices: false,
        trigger: 'hover'
    });
});

//--------------------------------------------------------------------------------------//
//                              GRIDSTER DRAG AND DROP FUNCTIONALITY                    //
//--------------------------------------------------------------------------------------//

//var gridster;
//$kpi(function () {
//    gridster = $kpi(".gridster ul").gridster({
//        widget_base_dimensions: [120, 160],
//        widget_margins: [5, 5],
//        draggable: {
//            handle: 'header'
//        },
//        max_cols: 8,
//        autogrow_cols: true,
//        resize: {
//            enabled: false
//        }
//    }).data('gridster');
//    // resize widgets on hover
//    var sizex, sizey;
//    gridster.$el.on('click', '> li footer a:nth-last-of-type(3)', function () {
//          sizex = $kpi(this).closest("li").attr("data-sizex");
//          sizey = $kpi(this).closest("li").attr("data-sizey");
//          //if (Number(sizex) < 5 && Number(sizey) === 4) {
//          //    gridster.resize_widget(($kpi(this).closest("li")), 2, 2);
//          //}
//          //else {
//          //    gridster.resize_widget(($kpi(this).closest("li")), 4, 4);
//          //}
//          if (($kpi(this).closest("li").find("div").attr("class")) === 'tilediv')
//          {
//              if (Number(sizex) < 5 && Number(sizey) === 3)
//                  gridster.resize_widget(($kpi(this).closest("li")), 2, 1);
//              else
//                  gridster.resize_widget(($kpi(this).closest("li")), 2, 3);
//          }
//          else if (($kpi(this).closest("li").find("div").attr("class")) === 'chartsdiv')
//          {
//              if (Number(sizex) < 5 && Number(sizey) === 5)
//                  gridster.resize_widget(($kpi(this).closest("li")), 4, 3);
//              else
//                  gridster.resize_widget(($kpi(this).closest("li")), 4, 5);
//          }
//          else if (($kpi(this).closest("li").find("div").attr("class")) === 'griddiv') {
//              if (Number(sizex) < 5 && Number(sizey) === 3)
//                  gridster.resize_widget(($kpi(this).closest("li")), 4, 2);
//              else
//                  gridster.resize_widget(($kpi(this).closest("li")), 4, 3);
//          }
//          $kpi(this).closest("li").find('.MoreInfoPanel').toggleClass("display");
//          $kpi("#btnTest").text($kpi(this).find('span').text());
//          //alert($kpi("#btnText").text);
//          //__doPostBack('btnTest', 'OnClick');
//    })
//    gridster.$el.on('click', '> li footer a:nth-last-of-type(2)', function (e) {
//        e.preventDefault(); 
//        $kpi("#hdnAssignemntID").val(($kpi(this).closest("footer").find("input[type=hidden]").val()));
//        window.open("KPISettings.aspx?AssignmentID=" + $kpi("#hdnAssignemntID").val(), "_blank", "toolbar=no, scrollbars=yes, resizable=yes, width=1000, height=750");
//        //return true;
//    })
//    gridster.$el.on('click', '> li footer a:nth-last-of-type(1)', function (e) {
//        ShowPopUp();
//        e.preventDefault();
//        $kpi("#hdnAssignemntID").val(($kpi(this).closest("footer").find("input[type=hidden]").val()));
//        $kpi("[id*=chkKPIlist] input:checked").each(function () {
//            var id = $kpi(this).val();
//            if (id === $kpi("#hdnAssignemntID").val())
//                $kpi(this).prop('checked', false);
//        });
//        __doPostBack('IbtnViewKPI', 'OnClick');
//        //$kpi(this).closest("li").toggleClass("ControlHide");
//        //return true;
//    })
//    //.on('mouseleave', '> li', function () {
//    //    gridster.resize_widget($kpi(this), sizex, sizey);
//    //    sizex = null; sizey = null;
//    //});
//});


//--------------------------------------------------------------------------------------//
//                              KPI LOADING BASED ON SELECTION                          //
//--------------------------------------------------------------------------------------//

$kpi(function () {
    $kpi("#chk1").change(function () {
        $kpi("#tile1").toggleClass("display");
    });
    $kpi("#chk2").change(function () {
        $kpi("#tile2").toggleClass("display");
    });
    $kpi("#chk3").change(function () {
        $kpi("#tile3").toggleClass("display");
        var range_map = $kpi.range_map({
            '0:25:': 'green',
            '26:75': 'yellow',
            '100:': 'red'
        });
        $kpi('.inlinesparkline').sparkline('html', { type: 'line', height: '100px', defaultPixelsPerValue: '100px', valueSpots: range_map, lineColor: 'black', tooltipPrefix: 'Distance: ', tooltipSuffix: 'Kms' });
        $kpi('.inlinebar').sparkline('html', { type: 'bar', height: '100px', barColor: 'red', barWidth: '30px', barSpacing: '10px', value: ['1', '2', '3', '4', '5'], colorMap: range_map, tooltipPrefix: 'Distance: ', tooltipSuffix: 'Kms' });
    });
    $kpi("#chk4").change(function () {
        $kpi("#tile4").toggleClass("display");
        //if ($kpi(this).is(":checked"))
        //    $kpi("#lblSpeedViolationChartData").sparkline('html', { type: 'line', height: '100px', defaultPixelsPerValue: '100px', spotColor: 'red', lineColor:'black', tooltipPrefix: 'No of Violations: ' });
        //else
        //    $kpi("#lblSpeedViolationChartData canvas").remove();
    });
    $kpi("#chk5").change(function () {
        $kpi("#tile5").toggleClass("display");
    });
    $kpi("#chk6").change(function () {
        $kpi("#tile6").toggleClass("display");
    });
    $kpi("#chkKPIStatistics").change(function () {
        $kpi("#tileKPIStatistics").toggleClass("display");
    });
    $kpi("#IbtnViewKPI").click(function (e) {
        //e.preventDefault();
        //$kpi("[id*=chkKPIlist] input:checked").each(function () {
        //    selectedValues.push($kpi(this).Index());
        //});
        //if (selectedValues.length > 0) {
        //    alert("Selected Value(s): " + selectedValues);
        //} else {
        //    alert("No item has been selected.");
        //}
        $kpi("#tile1").toggleClass("display");
        $kpi("#tile2").toggleClass("display");
        $kpi("#tile3").toggleClass("display");
        //var range_map = $kpi.range_map({
        //    '0:25:': 'green',
        //    '26:75': 'yellow',
        //    '100:': 'red'
        //});
        //$kpi('.inlinesparkline').sparkline('html', { type: 'line', height: '100px', defaultPixelsPerValue: '100px', valueSpots: range_map, lineColor: 'black', tooltipPrefix: 'Distance: ', tooltipSuffix: 'Kms' });
        //$kpi('.inlinebar').sparkline('html', { type: 'bar', height: '100px', barColor: 'red', barWidth: '30px', barSpacing: '10px', value: ['1', '2', '3', '4', '5'], colorMap: range_map, tooltipPrefix: 'Distance: ', tooltipSuffix: 'Kms' });
        $kpi("#tile4").toggleClass("display");
        $kpi("#tile5").toggleClass("display");
        $kpi("#tile6").toggleClass("display");
    });
});


//--------------------------------------------------------------------------------------//
//                              GOOGLE CHARTS API 1.0 INSTANTIATION                     //
//--------------------------------------------------------------------------------------//

// Load the Visualization API and the piechart package.
//google.load('visualization', '1.0', { 'packages': ['corechart'] });

// Set a callback to run when the Google Visualization API is loaded.
//google.setOnLoadCallback(drawChart);

// Callback that creates and populates a data table,instantiates the pie chart, passes in the data and draws it.
//function drawChart() {

// Create the data table array.
//    var data = new google.visualization.arrayToDataTable([
//        ['Bands', 'No.of.Vehicles', { role: 'style' }],
//        ['Safe', 9, '#D0FA58'],
//        ['Warning', 6, '#FFBF00'],
//        ['Critical', 3, '#FE642E'],
//    ]);

// Set chart options
//    var options = {
//        width: 500,
//        height: 400,
//        title: 'Vehicle: All; Period: Week; Range: Min-10,Max-15',
//        colors: ['#D0FA58', '#FFBF00', '#FE642E'],
//        chartArea: { width: '50%' },
//        hAxis: {
//            title: 'KPI Bands',
//            minValue: 0
//        },
//        vAxis: {
//            title: 'No.of.Vehicles'
//        },
//        legend: { position: "none" }
//    };

// Instantiate and draw our chart, passing in some options.
//    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
//    chart.draw(data, options);
//}


//--------------------------------------------------------------------------------------//
//                              GRID STACK RESPONSIVE PLUGIN DESIGN                     //
//--------------------------------------------------------------------------------------//
var gstack, serializedData;
$kpi(function () {
    var options = {
        cellHeight: 160,
        cellWidth: 200,
        verticalMargin: 20,
        disableResize: true
    };
    $kpi('.grid-stack').gridstack(options);
    $kpi('.grid-stack').addTouch();
});



$kpi(document).ready(function () {
    $kpi('.grid-stack-item').each(function () {
        gstack = $kpi(this).data('_gridstack_node');
        if (typeof gstack == 'undefined')
            return;
        //console.log(node);
        //gstack.el
        var gstack_moreinfo = gstack.el.children(".grid-stack-item-content").children("footer").children(".foo_moreinfo");
        gstack_moreinfo.on('click', gstack_moreinfo, function (e) {
            //var grid = $kpi('.grid-stack').data('gridstack');
            var grid = $kpi(this).closest('.grid-stack').data('gridstack');
            var item = $kpi(this).closest("div[data-gs-id]").data("_gridstack_node");
            var disptype =
            $kpi(this).closest("div").find('.MoreInfoPanel').toggleClass("display");
            if ($kpi(this).closest("div[data-gs-id]").children("div").children("div").attr("class") === 'tilediv') {
                if (item.height === 1)
                    grid.resize(item.el, item.width, 3);
                else
                    grid.resize(item.el, item.width, 1);
            }
            if ($kpi(this).closest("div[data-gs-id]").children("div").children("div").attr("class") === 'chartsdiv') {
                if (item.height === 3)
                    grid.resize(item.el, item.width, 5);
                else
                    grid.resize(item.el, item.width, 3);
            }
            if ($kpi(this).closest("div[data-gs-id]").children("div").children("div").attr("class") === 'griddiv') {
                if (item.height === 2)
                    grid.resize(item.el, item.width, 3);
                else
                    grid.resize(item.el, item.width, 2);
            }
        });

        //gstack.el.on('click', gstack.el.children(".grid-stack-item-content").children("footer").children("a:nth-last-of-type(2)"), function (e) {
        //    e.preventDefault();
        //    $kpi("#hdnAssignemntID").val(($kpi(this).closest("footer").find("input[type=hidden]").val()));
        //    window.open("KPISettings.aspx?AssignmentID=" + $kpi("#hdnAssignemntID").val(), "_blank", "toolbar=no, scrollbars=yes, resizable=yes, width=1000, height=750");
        //    //return true;
        //});

        var gstack_edit = gstack.el.children(".grid-stack-item-content").children("footer").children("a:nth-last-of-type(2)");
        gstack_edit.on('click', gstack_edit, function (e) {
            e.preventDefault();
            $kpi("#hdnAssignemntID").val(($kpi(this).closest("footer").find("input[type=hidden]").val()));
            var win = window.open("KPISettings.aspx?AssignmentID=" + $kpi("#hdnAssignemntID").val(), "_blank", "toolbar=no, scrollbars=yes, resizable=yes, width=1200, height=750");
            var Udp = document.getElementById('updKPITiles');
            var timer = setInterval(function () {
                if (win.closed) {
                    clearInterval(timer);
                    ShowPopUp();
                    __doPostBack('IbtnViewKPI', 'OnClick');
                    //window.location.href = 'KPIDashboard.aspx';
                    HidePopUp();
                }
            }, 100);
            //return true;
        });

        var gstack_delete = gstack.el.children(".grid-stack-item-content").children("footer").children("a:nth-last-of-type(1)");
        gstack_delete.on('click', gstack_delete, function (e) {
            ShowPopUp();
            e.preventDefault();
            $kpi("#hdnAssignemntID").val(($kpi(this).closest("footer").find("input[type=hidden]").val()));
            $kpi("[id*=chkKPIlist] input:checked").each(function () {
                var id = $kpi(this).val();
                if (id === $kpi("#hdnAssignemntID").val())
                    $kpi(this).prop('checked', false);
            });
            __doPostBack('IbtnViewKPI', 'OnClick');
            //$kpi(this).closest("li").toggleClass("ControlHide");
            //return true;
        });
    });
});

//});

function SaveGridPosition() {
    serializedData = _.map($kpi('.grid-stack > .grid-stack-item:visible'), function (el) {
        el = $kpi(el);
        var node = el.data('_gridstack_node');
        return {
            AssignmentId: node.id,
            x: node.x,
            y: node.y,
            width: node.width,
            height: node.height
        };
    }, this);
    //console.log(JSON.stringify(this.serializedData, null, '    '));
    document.getElementById('hdnKPIPositions').value = JSON.stringify(this.serializedData, null, '    ');
    //alert(document.getElementById('hdnKPIPositions').value);
    //__doPostBack('btnSavePosition', 'OnClick');
}

