(function (semusiCommonData, $, undefined) {


	var maxValue = 0;

	semusiCommonData.referalMapping;
	semusiCommonData.Dataset;
	semusiCommonData.populateSourceWiseInstallsUninstalls = function(platform){

    	maxValue = 0;
        
    	var sources = semusiCommonData.getUniqueSources(semusiCommonData.Dataset,platform);
    	var tableData = [];
        
        var otherRow = {
            source:"Other",
            avg_cpi:"",
            I:0,
            U:0,
            total:0
        };

        var platforms = ['android','ios', 'web'];
        var data = semusiCommonData.Dataset;
    	for(var y=0;y<sources.length;y++){
    		var row = {};
    		
            var installs=0;
            var uninstalls=0;
            var avgcpi = 0;
            var uniqueInstalls   = 0;
            var uniqueUninstalls = 0;

            for(var x=0; x<platforms.length; x++){
                if(data[platforms[x]]){
                    if(platforms[x].toLowerCase() == platform || platform == 'all'){
                        for(var z=0; z<data[platforms[x]].length; z++){
                            if(data[platforms[x]][z][sources[y]]){
                                var rec = data[platforms[x]][z][sources[y]];
                                var keys = Object.keys(data[platforms[x]][z][sources[y]]);
                                keys.forEach(function(value){
                                    if(value){
                                        if(value == 'in' || value == 'ri'){
                                            installs += rec[value];
                                        }
                                        if(value == 'in'){
                                            uniqueInstalls += rec[value];
                                        }
                                        if(value == 'un' || value == 'ru'){
                                            uninstalls += rec[value];
                                        }
                                        if(value == 'un'){
                                            uniqueUninstalls += rec[value];
                                        }

                                        if(value == 'cpi'){
                                            avgcpi =  rec[value];
                                        }
                                    }                                
                                });
                            }                        
                        }
                    }
                }
            } 
            //When installs is 0 and uninstall is > 0 then it means install value is put in others, so uninstall has to be pu t to others as well. 
            if(installs > 0 || uninstalls > 0){
                row.source=sources[y];
                row.avg_cpi= parseFloat(avgcpi).toFixed(2);
                row.I = installs;
                row.U = uninstalls;
                row.UINS = uniqueInstalls;
                row.UUNINS = uniqueUninstalls;
                row.percent = (uninstalls==0)? "0%" : parseFloat((uninstalls / installs)*100).toFixed(2) +"%";
                tableData.push(row);    

                installs = 0;
                uninstalls = 0;
            }
            else if(installs == 0 && uninstalls > 0){
                //When we have this scenario, it means installs are grouped to others
                otherRow.U = otherRow.U + uninstalls;
            }
            
        }
        if(otherRow.I>0){
            otherRow.percent = parseFloat((otherRow.U / otherRow.I)*100).toFixed(2) +"%";
            tableData.push(otherRow);    
        }
        
        
        $('#tblSources > tbody >tr').remove();	
        $('#tblSourcesAll > tbody >tr').remove();  
        var index=1;
        var max_i=0;
        var max_u=0;
        tableData.forEach(function(item){
            if(item.I>max_i){
                max_i = item.I;
            }
            if(item.U>max_u){
                max_u = item.U;
            }

            if(item.source == 'Self' || item.source == 'self'){
                item.source = 'Organic';
            }

            item.percent = (item.percent == 'Infinity%')? '0%': item.percent;
            if(index<6){
                $('#tblSources > tbody').append('<tr><td style="padding-right:5px;text-align:right;">'+item.avg_cpi +'</td><td style="padding-right:5px;text-align:right;">'+item.UINS+' (' + item.I +')</td><td style="text-align:right;padding:3px;border:none"><div style="float:right" id="i_'+index+'">&nbsp;</div></td><td style="text-align:center">'+ semusiCommon.toFirstUpper(item.source) +'</td><td style="padding:3px;text-align:left;;border:none"><div style="float:left" id="u_'+ index +'">&nbsp;</div></td><td style="padding-right:5px;text-align:right;">'+item.UUNINS+' ('+ item.U + ')</td><td style="text-align:center;color:white;font-weight:bold;" id="td_'+index+'">'+ item.percent +'</td></tr>');      
            }       

            $('#tblSourcesAll > tbody').append('<tr><td style="padding-right:5px;text-align:right;">'+ item.avg_cpi+'</td><td style="padding-right:5px;text-align:right;">'+item.UINS+' (' + item.I +')</td><td style="text-align:right;padding:3px;border:none"><div style="float:right" id="i_all_'+index+'">&nbsp;</div></td><td style="text-align:center">'+ semusiCommon.toFirstUpper(item.source) +'</td><td style="padding:3px;text-align:left;;border:none"><div style="float:left" id="u_all_'+ index +'">&nbsp;</div></td><td style="padding-right:5px;text-align:right;">'+item.UUNINS+' ('+ item.U + ')   </td><td style="text-align:center;color:white;font-weight:bold;" id="td_all_'+index+'">'+ item.percent +'</td></tr>');
            index++;
        });
        if(tableData.length>5){
            //$('#tblSources > tbody').append('<tr ><td colspan="6" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer" onclick="showAllSources();">+more</td></tr>'); 
            $("#lnkMoreSources").show();
        }
        else{
            $("#lnkMoreSources").hide();
        }

        //format color bands.
        for(var i=0;i<tableData.length;i++){
            var i_percent = parseInt((tableData[i].I/max_i)*100);
            var u_percent = parseInt((tableData[i].U/max_i)*100);
            
            //if percentage comes out to be zero, then i am assigning 1 so that color band looks good.
            if(i_percent==0){
                i_percent = 1;
            }
            if(u_percent==0){
                u_percent = 1;
            }
            else if(u_percent>100){
                u_percent = 100;
            }

            $("#i_"+(i+1)).css("background","blue");
            $("#i_"+(i+1)).css("width", i_percent+"%");
            $("#i_all_"+(i+1)).css("background","blue");
            $("#i_all_"+(i+1)).css("width", i_percent+"%");

            $("#u_"+(i+1)).css("background","red");
            $("#u_"+(i+1)).css("width", u_percent+"%");
            $("#u_all_"+(i+1)).css("background","red");
            $("#u_all_"+(i+1)).css("width", u_percent+"%");

            var percent = (tableData[i].I > 0)? tableData[i].U/tableData[i].I : 0;
            var bgcolor = getGradientColor('#00FF00', '#FF0000', percent);
            bgcolor = bgcolor.replace("-","");
            bgcolor = bgcolor.substr(0, 7);
            $("#td_"+(i+1)).css("background",bgcolor);
            $("#td_all_"+(i+1)).css("background",bgcolor);

        }
    } 
    
    semusiCommonData.getUniqueSources = function(data,platform){
    	var sources=[];
        if(data){
            var platformsArray = Object.keys(data);
            for(var x=0; x<platformsArray.length; x++){
                if(platformsArray[x].toLowerCase() == platform || platform == 'all'){
                    var obj = data[platformsArray[x]];
                    obj.forEach(function(objVal){
                        if(objVal){
                            var s = Object.keys(objVal);                            
                            if(sources.indexOf(s[0]) == '-1'){  
                                sources.push(s[0]); 
                            } 
                        }  
                    });
                }
            }
            /*for(var x=0;x< data.length;x++){
                if(data[x].ref && ((data[x].p && data[x].p.toLowerCase() == platform) || platform == 'all')){
                    var label = getSource(data[x].ref.toLowerCase());
                    if ($.inArray(label, sources) == -1 ) {
                        sources.push(label);
                    }

                    if(data[x].total > maxValue){
                        maxValue = data[x].total;
                    }    
                }
            } */  
        }
    	
        return sources;
    }

    getSource = function(source){
        var ref = source;
        for(var i=0; i<semusiCommonData.referalMapping.length; i++){
            if(source.indexOf(semusiCommonData.referalMapping[i].mstr.toLowerCase())>=0){
                ref=semusiCommonData.referalMapping[i].rstr;
                break;
            }
        }
        return ref;
    }

getGradientColor = function(start_color, end_color, percent) {
   // strip the leading # if it's there
   start_color = start_color.replace(/^\s*#|\s*$/g, '');
   end_color = end_color.replace(/^\s*#|\s*$/g, '');

   // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
   if(start_color.length == 3){
     start_color = start_color.replace(/(.)/g, '$1$1');
   }

   if(end_color.length == 3){
     end_color = end_color.replace(/(.)/g, '$1$1');
   }

   // get colors
   var start_red = parseInt(start_color.substr(0, 2), 16),
       start_green = parseInt(start_color.substr(2, 2), 16),
       start_blue = parseInt(start_color.substr(4, 2), 16);

   var end_red = parseInt(end_color.substr(0, 2), 16),
       end_green = parseInt(end_color.substr(2, 2), 16),
       end_blue = parseInt(end_color.substr(4, 2), 16);

   // calculate new color
   var diff_red = end_red - start_red;
   var diff_green = end_green - start_green;
   var diff_blue = end_blue - start_blue;

   diff_red = ( (diff_red * percent) + start_red ).toString(16).split('.')[0];
   diff_green = ( (diff_green * percent) + start_green ).toString(16).split('.')[0];
   diff_blue = ( (diff_blue * percent) + start_blue ).toString(16).split('.')[0];

   // ensure 2 digits by color
   if( diff_red.length == 1 )
     diff_red = '0' + diff_red

   if( diff_green.length == 1 )
     diff_green = '0' + diff_green

   if( diff_blue.length == 1 )
     diff_blue = '0' + diff_blue

   return '#' + diff_red + diff_green + diff_blue;
 };
}(window.semusiCommonData = window.semusiCommonData || {}, jQuery));