<?php
list($a, $b) = explode(' ', $this->header);
$checked_string = isset($this->params['checked_options']) ? $this->params['checked_options'] : array();
$breakdownCheckedValuesString = isset($this->params['breakdownCheckedValues']) ? $this->params['breakdownCheckedValues'] : '';
$allFlag = $this->params['allFlag'];
$checkedOptions = array();
if (!empty($breakdownCheckedValuesString)) {
    $checkedOptions = explode(',', $breakdownCheckedValuesString);
}
if (!is_array($checked_string)) {
    $checked_options = explode(',', $checked_string);

} else {
    $checked_options = $checked_string;
}
$sourcePage = 'channel';

$totalcount = $this->params['totalCount'];
if (isset($this->params['pagerPage'])) {
    $setCount = 'on';
} else {
    $setCount = ($this->params['totalCount'] > 20)? 'off' : $this->params['setCount'];
}
$defaultCheck = true;
$highestPercentage = $this->params['highestPercentage'];
$group_by_label = lcfirst($this->params['group_by']);
if ($group_by_label == 'country') {
    $group_by_label = 'countries';
} else if ($group_by_label == 'isrc') {
    $group_by_label = 'track';
} else if ($group_by_label == 'catalog') {
    $group_by_label = 'album';
}
?>

<div class="channelCharts">
<div id="<?=strtolower($a) . ucfirst($b)?>" class="analyticsChannelTable">
<div class="analyticsChannelTableHeader table_header">
    <div class="analyticsCheckbox"></div>
    <div id="tableStoreCountry"><?=$this->translate(ucfirst($group_by_label))?></div>
    <div id="tableUnits"><?=$this->translate('Units Sold')?></div>
    <span id="tablePercent">%</span>
</div>
    <ul class="zebra_stripe_with_subs">
        <li class="analyticsTableRow allData">
        <?php $defaultCheck = false; ?>
            <div class="analyticsCheckbox"><input type="checkbox" class="brk_checkbox" value="all" /></div>
            <div class="rowStoreCountry" title="All <?=ucwords($group_by_label)?>">
                <?=$this->translate('All' . ucwords($group_by_label) . 's')?>
            </div>
            <div class="rowUnits">
                <b>
                    <?=$this->numberFormat($this->params['totalActivities'], $this->params['locale'])?>
                    <?=$this->translate('total' .strtolower($this->channel_info->full_name))?>, 
                    <?=$this->translate('across')?> 
                    <strong><span id="totalCountDisplay"></span></strong> 
                    <?=$this->translate(ucwords($group_by_label). 's')?>
                </b>
            </div>
            <div class="rowPercent">100.00%</div>
        </li>
        <form name="frm_breakdown" id="frm_breakdown">
        <?php
        $counter = 0;
        $firstPercentage = 0;
        $calculatedPixels = 0;
        foreach ($this->results as $i => $pseudoData) {
            $calculatedPixels = 285 * round($pseudoData['percentage'], 2) / $highestPercentage;
            if ($calculatedPixels > 285) {
                $calculatedPixels = 285;
            } else if ($calculatedPixels <= 1) {
                $calculatedPixels = 1;
            }
        ?>
        <li class="analyticsTableRow">
            <div class="analyticsCheckbox">
                <input <?=(((count($this->results) == 1) && ($defaultCheck == true ))  ? ' checked="checked" ' : '')?> type="checkbox"<?=in_array($pseudoData['objectId'], $checked_options) ? ' checked="checked" ' : '';?> class="brk_checkbox" value="<?=$pseudoData['objectId']?>" name="objectId[]" id="objectId" />
            </div>
            <div class="rowStoreCountry" title="<?php echo ($pseudoData['name'] == '') ? '&nbsp;' : $pseudoData['name'] ?>">
                <?php echo ($pseudoData['name'] == '') ? '&nbsp;' : $pseudoData['name'] ?>
            </div>
            <?php
            if (($this->params['group_by'] == 'isrc' || $this->params['group_by'] == 'catalog') && isset($pseudoData['childCount']) &&  $pseudoData['childCount'] > 1) {?>
                <script>$("#<?=strtolower($a) . ucfirst($b)?>").addClass("expandable");</script>
                <div class="expandRow" id="<?=$pseudoData['objectId']?>" parentWidth="<?=$calculatedPixels?>"></div>
            <?php
            }
            ?>
            <div class="rowUnits">
                <div class="unitsNumber"><?=$this->numberFormat($pseudoData['total'], $this->params['locale'])?></div>
                <div id="<?=$pseudoData['objectId']?>bar" class="unitsBar" style="width:<?=$calculatedPixels?>px"></div>
                <div class="clear"></div>
            </div>
            <div class="rowPercent"><?=sprintf('%1.2f', round($pseudoData['percentage'], 2))?>%</div>
            <div class="clear"></div>
        </li>
        <li class="additionalTableRow" id="subrows_cat<?=$pseudoData['objectId']?>" style="display:none;"></li>
        <?php
        }
        ?>
        </form>
        <span id="paginationButton">
            <a id="breakdownNext" class="float-right pagination next" href="javascript:submitMyFrm('<?=$this->params['group_by']?>', 20, parseInt(<?=$this->params['pagerPage']?>) +1,'<?=$setCount?>', <?=$this->params['totalActivities']?>, <?=$highestPercentage?>);"><span></span></a>
        </span>
        <?php
        if (($prevPage = $this->params['pagerPage'] -1) > 0) { ?>
            <a id="breakdownPrev" class="float-right pagination prev" href="javascript:submitMyFrm('<?=$this->params['group_by']?>', 20, <?=$prevPage?>,'<?=$setCount?>', <?=$this->params['totalActivities']?>, <?=$highestPercentage?>);"><span></span></a>
        <?php
        }
        ?>
        <div class="clear"></div>
    </ul>
</div>
<div class="clear"></div>
</div>
<script>
//colors for breakdown: purple, green, orange, cyan,  red
var nameMap = {artist:"artistIds",catalog:"catalogIds",isrc:"isrcIds",store:"storeIds",country:"countryIds",genre:"genreIds",network:"socialIds"};
//var nameMap = {artist:"ba",catalog:"bc",isrc:"bi",store:"bs",country:"bct",genre:"bg",network:"bs"};
//var breakdownColors = ["#a513b2","#5fb22f","#fb6b1b","#24b5b4","#d80011"];
var breakdownColors = ["#a513b2","#5fb22f","#fb6b1b","#ff0000","#24b5b4"];
eval("var checkName = nameMap.<?=$this->params['group_by']?>");
var usedColor = [];
var selectedItems = [];
var tmpLineSet = {};
tmpLineSet["all"] = {line: "all", fill:.3, color: '#3399FF'};
var tmpObj = null;
currentPage = parseInt(<?=$this->params['pagerPage']?>);
channelSetCount = '<?=$setCount?>';
channelTotalActivities = <?=$this->params['totalActivities']?>;
channelHighestPercentage = <?=$highestPercentage?>;
var timeOut = null;
//On Click of breakdown checkboxes, update the graphs
$('.brk_checkbox').click(function (){
        tmpObj = this;
        var selcount = 0;
        if(selectedItems.length <= 0 ){
            selectedItems = [];
        }else{
            if(!$(tmpObj).attr("checked") && ($(tmpObj).attr("value")!="all") && ($('.brk_checkbox').length > 1) && (jQuery.inArray($(tmpObj).attr("value"),selectedItems) >= 0)) {
                var val = $(tmpObj).attr("value");
                var len = selectedItems.length;
                selectedItems.splice(jQuery.inArray(val,selectedItems),1);

                var tmpVal = $(tmpObj).attr("value");
                var tmpColor = rgb2hex($("#"+tmpVal+"bar").css("backgroundColor"));
                $("#"+tmpVal+"bar").css("backgroundColor","#cccccc");
                usedColor.splice(jQuery.inArray(tmpColor,usedColor),1);
            }
            selcount = selectedItems.length;
        }
        var limit = 4;
        if(($('.brk_checkbox[value="all"]').attr("checked") == true) && ($(tmpObj).attr("value") == 'all')){
            selcount = parseInt(selcount) + 1;
            limit = 6;
        }else if(($('.brk_checkbox[value="all"]').attr("checked") == false) && ($(tmpObj).attr("value") == 'all') && (parseInt(selcount) < 5 )){
            selcount = parseInt(selcount) - 1;
            limit = 5;
        } else if($('.brk_checkbox[value="all"]').attr("checked") == false){
            limit = 5;
        }
        if(parseInt(selcount) < limit){
            clearTimeout(timeOut);
            if($('.brk_checkbox').length == 1){
                $('.brk_checkbox').attr('checked',true);
                return;
            }
            if($(tmpObj).attr("value")!="all"){
                if($(tmpObj).attr("checked")){
                    var tmpVal = $(tmpObj).attr("value");
                    var colorsNotUsed = $.grep(breakdownColors, function($e) { return $.inArray($e, usedColor) == -1; });
                    tmpLineSet[tmpVal] = {line: tmpVal, color: colorsNotUsed[0]};
                    usedColor.push(colorsNotUsed[0]);
                    $("#"+tmpVal+"bar").css("backgroundColor",colorsNotUsed[0]);
                }
            }else{
                tmpVal = "all";
            }
            if($(tmpObj).attr("checked")){
                if(colorsNotUsed == undefined){
                    tt.selectedBreakdownItems.push({groupby:tt.selectedBreakdownGroup,item:tmpVal});
                }else{
                    tt.selectedBreakdownItems.push({groupby:tt.selectedBreakdownGroup,item:tmpVal,color:colorsNotUsed[0]});
                }
            }else{
                for(var z in tt.selectedBreakdownItems){
                    if(tt.selectedBreakdownItems[z].groupby == tt.selectedBreakdownGroup && tt.selectedBreakdownItems[z].item == tmpVal){
                        tt.selectedBreakdownItems.splice(z,1);
                    }
                }
            }
            $('.brk_checkbox[value!="all"]:checked').each(function(i,s){
                var tmpValue = $(s).attr("value");
                //selectedItems.push(tmpValue);
                if(($.inArray(tmpValue,selectedItems)) == -1) {
                    selectedItems.push(tmpValue);
                }
            });
            if(selectedItems.length > 0){
                if($('.brk_checkbox[value="all"]').attr("checked")){
                    timeOut = setTimeout("tt.getLineGraphData('<?=$sourcePage?>', '<?=$this->params['group_by']?>', selectedItems, tmpLineSet, true, 'channeldetailcheckbox')", 2000);
                }else{
                    timeOut = setTimeout("tt.getLineGraphData('<?=$sourcePage?>', '<?=$this->params['group_by']?>', selectedItems, tmpLineSet, false, 'channeldetailcheckbox')", 2000);
                }
            }else{
                $('.brk_checkbox[value="all"]').attr("checked",true);
                <?php
                if ($sourcePage == "social") {
                    if ($this->params['channel'] != "Fans") { ?>
                        var allData = [];
                        allData.push($.extend(true,[],tt.totalCombinedLineSet['<?=$this->params['channel']?>'][0]));
                        var tmpRes = {results:{<?=$this->params['channel']?>:allData}};
                        tt.drawSocialGraph('<?=$this->params['channel']?>', tmpRes, tmpLineSet);
                    <?php
                    } else {
                    ?>
                        var filterData = $("#frm_filter").serializeArray();
                        filterData.push({name:"format",value:"json"});
                        filterData.push({name:"group_by",value:"date,<?=$this->params['group_by']?>"});
                        $.ajax({
                                 type: 'POST',
                                 url: '/analytics/setupsocialgraph',
                                 data: filterData,
                                 dataType: 'json',
                                 success: function( res, textStatus, XMLHttpRequest ){
                                             $("#loading_graph").hide();
                                            $(".channelInfo").show();
                                            $("#placeholderX").show();
                                             tt.drawSocialGraph($('#channel').val(),res, {all:{line: 'all', fill:.3, color: '#3399FF'}});
                                             $(".brk_checkbox").attr("disabled",false);
                                 },
                                 error: function( xhr, textStatus, errorThrown ){
                                     $("#loading_graph").hide();
                                    $(".channelInfo").show();
                                    $("#placeholderX").show();
                                  }
                            });
                            <?php
                    } ?>
                <?php
                } else {
                ?>
                    var tmpRes = {results:{all:tt.totalCombinedLineSet, events:tt.totalCombinedEventSet}};
                    eventCount = 1;
                    tt.submit({page:pageview,company:vendorCompanyName});
                    filterFlag = "on";
                <?php
                }
                ?>
            }
        }else{
            $(tmpObj).attr("checked",false);
        }
        if(($(".brk_checkbox:checked").length == 0) && currentPage == 1){
            $('.brk_checkbox[value="all"]').attr("checked",true);
            tt.submit({page:pageview,company:vendorCompanyName});
        }
});

$('.expandRow').click(function() {
    var myId = $(this).attr('id');
    if ($('#subrows_cat'+myId).is(":hidden")) {
    <?php if ($this->params['group_by'] == 'catalog') { ?>
        trackGAEvent('Analytics', 'Release Version Details', {type:'expand',catalogId:myId});
    <?php } else { ?>
        trackGAEvent('Analytics', 'Track Version Details', {type:'expand',isrcId:myId});
    <?php } ?>
    }else{
    <?php if ($this->params['group_by'] == 'catalog') { ?>
        trackGAEvent('Analytics', 'Release Version Details', {type:'collapse',catalogId:myId});
    <?php } else { ?>
        trackGAEvent('Analytics', 'Track Version Details', {type:'collapse',isrcId:myId});
    <?php } ?>
    }
    if ($('#subrows_cat'+myId).is(":visible")) {
        $('#subrows_cat'+myId).hide();
        $(this).css("background-position",'0 0px');
    }else {
        $('#subrows_cat'+myId).html('<div id="loading_image2"><img src="/images/loading.gif" /><br style="clear: both"></div>');
        $('#subrows_cat'+myId).show();

        myObj = getMyObj();
        myObj['group_by'] = "
        <?php
        if ($this->params['group_by'] == 'catalog') {
            echo 'release';
        } else {
            echo 'track';
        }
        ?>
        ";
        myObj['format'] = 'json';
        myObj[checkName] = myId;
        myObj['breakdown'] = 1;
        myObj['setCount'] = "<?=$this->params['setCount']?>";
        myObj['totalActivities'] = <?=$this->params['totalActivities']?>;
        myObj['totalActivitiesPaid'] = <?=$this->params['totalActivitiesPaid']?>;
        myObj['parentWidth'] = $(this).attr("parentWidth");

        var parentObj = $(this);

        $.ajax({
            type: 'POST',
            url: '/analytics/channeldetail',
            data: myObj,
            dataType: "json",
            success: function( objResponse, textStatus, XMLHttpRequest ){
                $('#subrows_cat'+myId).html(objResponse.html);
                parentObj.css("background-position",'0 -23px');
            },
            error: function( xhr, textStatus, errorThrown ){
                $('#subrows_cat'+myId).html("Error occured");
             }
        });
    }
});

$('.channelCharts li.analyticsTableRow:even').addClass('even');

$(document).ready(function(){
    if(pageloadSelect == 0){
        pageloadSelect =1;
        <?php
        if (count($checkedOptions) > 0) {
            foreach ($checkedOptions as $key => $value) { ?>
                var tmpVal = '<?php echo $value; ?>';
                var colorUse = breakdownColors[<?php echo $key;?>];
                tt.selectedBreakdownItems.push({groupby:"<?=$this->params['group_by']?>",item:tmpVal,color:colorUse});
                tt.selectedBreakdownGroup = "<?=$this->params['group_by']?>";
            <?php
            }
            if ($allFlag == 'true') { ?>
                tt.selectedBreakdownItems.push({groupby:"<?=$this->params['group_by']?>",item:'all'});
            <?php
            }
        } ?>

    }
    if((myObj.pagerPage * 20) < totalRowCount){
        $('#paginationButton').show();
    }else if((myObj.pagerPage == undefined) && (totalRowCount > 20)){
        $('#paginationButton').show();
    }else{
        $('#paginationButton').hide();
    }

    if(totalRowCount > 1){
        $('.allData').show();
    }else{
        $('.allData').remove();
    }
    $('#totalCountDisplay').html(formatNumber(totalRowCount,delimiter));//formatNumber(totalRowCount,',') //formatNumber(totalRowCount,delimiter)
if(totalRowCount == 1){
        $("#objectId").attr("checked",true);
        selectedItems = [];
        var tmpVal = $("#objectId").attr("value");
        var colorsNotUsed = $.grep(breakdownColors, function($e) { return $.inArray($e, usedColor) == -1; });
        tmpLineSet[tmpVal] = {line: tmpVal, color: colorsNotUsed[0]};
        usedColor.push(colorsNotUsed[0]);
        $("#"+tmpVal+"bar").css("backgroundColor",colorsNotUsed[0]);
        $('.brk_checkbox[value!="all"]:checked').each(function(i,s){
            var tmpValue = $(s).attr("value");
            selectedItems.push(tmpValue);
        });
        tt.getLineGraphData('<?=$sourcePage?>','<?=$this->params['group_by']?>', selectedItems, tmpLineSet, false, "channeldetailcheckbox");
}else{
        if(tt.selectedBreakdownItems.length > 0){
            var drawAll = false;
            for(var i in tt.selectedBreakdownItems){
                if(tt.selectedBreakdownItems[i].groupby == '<?=$this->params['group_by']?>'){
                    var tmpVal = tt.selectedBreakdownItems[i].item;
                    var tmpCol = tt.selectedBreakdownItems[i].color;
                    $(".brk_checkbox[value=all]").attr("checked",false);
                    if(tmpVal == "all"){
                        drawAll = true;
                        $(".brk_checkbox[value=all]").attr("checked",true);
                    }else{
                        $(".brk_checkbox[value="+tmpVal+"]").attr("checked",true);
                        tmpLineSet[tmpVal] = {line: tmpVal, color: tmpCol};
                        usedColor.push(tmpCol);
                        $("#"+tmpVal+"bar").css("backgroundColor",tmpCol);
                        selectedItems.push(tmpVal);
                    }
                }
            }
            if(selectedItems.length > 0){
                tt.getLineGraphData('<?=$sourcePage?>',tt.selectedBreakdownGroup, selectedItems, tmpLineSet, drawAll, "channeldetailcheckbox");
            }
        }
        if(($(".brk_checkbox:checked").length == 0) && (selectedItems.length == 0)){
            tt.selectedBreakdownItems.push({groupby:'<?=$this->params['group_by']?>',item:'all'});
            $(".brk_checkbox[value=all]").attr("checked",true);
        }
        if($(".brk_checkbox[value=all]").attr("checked") == true){
            var tmpRes = {results:{all:tt.totalCombinedLineSet, events:tt.totalCombinedEventSet}};
            eventCount =1;
            filterFlag = "on";
            tt.drawChannelGraphs(tmpRes, tmpLineSet);
        }
        for(var i in tt.selectedBreakdownItems){
            if(tt.selectedBreakdownItems[i].groupby == '<?=$this->params['group_by']?>' && tt.selectedBreakdownItems[i].item == 'all'){
                $(".brk_checkbox[value=all]").attr("checked",true);
            }
        }
    }
});

</script>
