/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/
(function($){
    $(function () {
        // keep state of disableFlash checkbox
        var $flashSwitch = $('input[name=disableFlash]');
        $flashSwitch.change(function () {
            if ($(this).is(':checked')) {
                $.setCookie('disableFlash', 1);
            } else {
                $.setCookie('disableFlash', 0);
            }
        });

        if ($.getCookie('disableFlash')) {
            $flashSwitch.attr('checked', 'checked');
        }

        // update filters if we have "current" zone
        if(currentItemId) {
            $('div.StatsFilterPopup').each(function(){
                if($('a.'+$(this).attr('id')).parent().is(':visible')) {
                    $('ul.statFilters li a', this).each(function () {
                        if ($(this).attr('data-filter') != currentItemId) {
                            $(this).removeClass('checked');
                        }
                    });
                }
            });
        }

        $('a.disableLink').click(function (evt) {
            evt.preventDefault();
        });
        // handle date shortcut links
        $('.dateShortcut a').click(function (evt) {
            evt.preventDefault();
            $(this).parents('.graphContainer').find("input.generateStats").trigger('click', $(this).attr('data-date'));
        });

        $('div.StatsFilterPopup ul li a').click(function (evt) {
            evt.preventDefault();
            evt.stopPropagation();

            if ($(this).hasClass('checked')) {
                $(this).removeClass('checked');
            } else {
                $(this).addClass('checked');
            }

            var hasClass = false;

            $('ul li a', $(this).parent('div.zoneFilter')).each(function (index, el) {
                if ($(el).hasClass('checked')) {
                    hasClass = true;
                }
            });

            if (hasClass) {
                $('a.zoneFilterLink').addClass('active');
            } else {
                $('a.zoneFilterLink').removeClass('active');
            }
        });

        $("input.generateStats").click(function (evt, dateInterval) {
            var $buttonElem = $(this);
            var $graphContainer = $buttonElem.parents(".graphContainer");
            var $graphImageContainer = $('.graphImageContainer', $graphContainer);
            var dataId = $buttonElem.attr('data-id');
            var dataUrl = $buttonElem.attr('data-url');
            var functionName = $buttonElem.attr('data-function');

            $graphImageContainer.html('').removeClass('empty');

            if (!$graphImageContainer.hasClass('progress')) {
                $graphImageContainer.addClass('progress');
            }

            if (dataId) {
                var filter = [];

                $('div#' + dataId + ' ul li a.checked').each(function (index, el) {
                    filter[filter.length] = $(el).attr('data-filter');
                });

                if (filter.length == 0) {
                    $graphImageContainer.removeClass('progress').addClass('empty').html($buttonElem.attr('data-error'));
                    return;
                }
            }

            var from = $('input[name=from]', $graphContainer).val();
            var to = $('input[name=to]', $graphContainer).val();
            var disableFlash = $('input[name=disableFlash]', $graphContainer).is(':checked');

            $.ajax({
                url: dataUrl,
                'success': function (response) {

                    $graphImageContainer.removeClass('progress');

                    if (response.error) {
                        $graphImageContainer.addClass('empty').html(response.error);
                        return;
                    }

                    if (dateInterval) {
                        if (response.data.from) {
                            $('input[name=from]', $graphContainer).val(response.data.from);
                        }
                        if (response.data.to) {
                            $('input[name=to]', $graphContainer).val(response.data.to);
                        }
                    }

                    window[functionName]($graphImageContainer, response.data, disableFlash);
                },
                complete: function (response, status) {
                    $graphImageContainer.removeClass('progress');
                    if (status != 'success' && status != 'notmodified') {
                        try {
                            var data = $.parseJSON(response.responseText);

                            try {
                                $graphImageContainer.html(data.error);
                            } catch ($ex1) {
                                $graphImageContainer.html(data);
                            }
                        } catch ($ex2) {
                            $graphImageContainer.html(response.responseText);
                        }
                    }
                },
                data: {
                    'from': from,
                    'to': to,
                    'filter': filter,
                    'dateInterval': dateInterval,
                    'currentDataId': currentItemId,
                    _xfResponseType: 'json',
                    _xfToken: XenForo._csrfToken
                },
                type: 'GET',
                dataType: 'json'
            });
        });
    });
})(jQuery);

function XenCentral_AdServer_Draw_Line($container, data, disableFlash) {
	var dataTable = new google.visualization.DataTable();

	var columnIndexMap = {};

	var rowIndexCounter = {};

	var colCount = 0;

	for (var columnIndex in data.columns) {
		var column = data.columns[columnIndex];

		dataTable.addColumn(column.type, column.label)

		columnIndexMap[columnIndex] = colCount;

		rowIndexCounter[columnIndex] = 0;

		colCount++;
	}

	// convert first argument from unix timestamp to date object
	var rowIndex = 0;

	dataTable.addRows(data.dataCount);

	for (var dateline in data.rows) {
		var row = data.rows[dateline];

		for (var colIndex in row) {
			var dataCount = row[colIndex];

			dataTable.setValue(rowIndexCounter[colIndex], 0, new Date(dateline * 1000));
			dataTable.setValue(rowIndexCounter[colIndex], columnIndexMap[colIndex], dataCount);

			rowIndexCounter[colIndex]++;
		}
	}

	if (disableFlash) {
		var chart = new google.visualization.LineChart($container.get(0));
	} else {
		var chart = new google.visualization.AnnotatedTimeLine($container.get(0));
	}

	chart.draw(dataTable, {width: 750, height: 300, title: data.title, enableInteractivity:true, 'wmode':'transparent'});
}

function XenCentral_AdServer_Draw_Pie($container, data)
{
    var dataTable = new google.visualization.DataTable();

	for (var columnIndex in data.columns)
	{
		var column = data.columns[columnIndex];

		dataTable.addColumn(column.type, column.label)
	}
    try {
        dataTable.addRows(data.rows);
    } catch(ex) {
        console.log(ex.message);
    }


    // empty the container and create to elements
    $container.html('');

    var $pieChartContainer=$('<div class="statsCol"></div>').appendTo($container);
    var $tableChartContainer = $('<div class="statsCol"></div>').appendTo($container);

    var containerWidth= $container.width();

	var chart = new google.visualization.PieChart($pieChartContainer.get(0));
    chart.draw(dataTable, {width:containerWidth/2, height:300, title:data.title, enableInteractivity:true});

    var tableDataTable = jQuery.extend(true, {}, dataTable);
    tableDataTable.addRow([data.total_phrase, data.total]);

    var table = new google.visualization.Table($tableChartContainer.get(0));
    table.draw(tableDataTable, {width:containerWidth / 2, height:300, title:data.title, enableInteractivity:true});
}

function XenCentral_AdServer_Load_All_Stats()
{
    $('input.button.autoSubmit').click();
}