(function (semusiDemographics, $, undefined) {

	semusiDemographics.Interests;
	semusiDemographics.currenData;
	var topUserInterests;
  var competingAppUsers;
	var totalActiveUsers = 0;
	var barChartData = {
		labels : [],
		datasets : []
		
	};
  var barChartDataCompetingApps = {
    labels : [],
    datasets : []
    
  };
	//private functions
	populateUsersByGender = function(){
		var platforms = ["android","ios"];
        demographicData = [];
        for(var i=0;i<platforms.length;i++){
        	var row = {
        		male:0,
        		female:0,
        		unknown:0,
        	};
        	row.platform= semusiCommon.toFirstUpper(platforms[i]);
        	semusiDemographics.currenData.forEach(function(item){
				if((item.p && item.p.toLowerCase()==platforms[i]) && (item.gender && typeof(item.gender)==='string' && (item.gender.toLowerCase()=="male" || item.gender.toLowerCase()=="m" ))){
					row.male = row.male + item.total; 
				}
				else if((item.p && item.p.toLowerCase()==platforms[i]) && (item.gender && typeof(item.gender)==='string' && (item.gender.toLowerCase()=="female"  || item.gender.toLowerCase()=="f"))){
					row.female = row.female + item.total; 
				}
				else if((item.p && item.p.toLowerCase()==platforms[i]) ){
					row.unknown = row.unknown + item.total; 
				}	
			});
			row.total = row.male+row.female+row.unknown;
        	demographicData.push(row);
    	}

    	$('#tblGenderData > tbody >tr').remove();
    	var male=0,female=0,unknown=0,total=0;
    	demographicData.forEach(function(item){
        var platform = item.platform;
        if(platform == "Ios"){
          platform = "iOS";
        }

    		$('#tblGenderData > tbody').append('<tr><td style="padding:3px;">' +platform+'</td><td style="padding:3px;text-align:right">'+ item.male  +'</td><td style="padding:3px;text-align:right">'+ item.female + '</td><td style="padding:3px;text-align:right">'+ item.unknown + '</td><td style="padding:3px;text-align:right">'+ item.total + '</td></tr>'); 
    		male = male+item.male;
    		female = female+item.female;
    		unknown = unknown+item.unknown;
    		total = total+item.total;
    	});
    	$('#tblGenderData > tbody').append('<tr style="font-weight:bold;"><td style="padding:3px;">Total</td><td style="padding:3px;text-align:right">'+ male  +'</td><td style="padding:3px;text-align:right">'+ female + '</td><td style="padding:3px;text-align:right">'+ unknown + '</td><td style="padding:3px;text-align:right">'+ total + '</td></tr>'); 
    	$('#lblActiveUsers').text(total);
      totalActiveUsers = total;
		
	}

  	function handleChartJs() {
        $(window).load(function() {
            handleGenerateGraph();
            generateCompetingAppGraph()
        });
        
        $(window).resize( function() {
            handleGenerateGraph();
            generateCompetingAppGraph();
        });
    };

  	createBarChartData = function(){
  		barChartData = {
	  		labels : [],
	  		datasets : []
  		};
  		var labels=[];
  		var data=[];
      var backgroundColor = [];
      var borderColor = []
	      
	    if(semusiDemographics.Interests==undefined){return;}
  		for(var i=0;i<semusiDemographics.Interests.length ;i++){
            labels.push(semusiDemographics.Interests[i].interest);
            data.push(semusiDemographics.Interests[i].interestValue);  

            // graph color manage
            var gColor = semusiCommon.getRandomColor();
            backgroundColor.push(gColor);
            borderColor.push(gColor);
	  	}

      barChartData = {
          type: 'horizontalBar',
          data: {
              labels: labels,
              datasets: [{
                  label: '',
                  data: data,
                  backgroundColor: backgroundColor,
                  borderColor: borderColor,
                  borderWidth: 1
              }]
          },
          options: {
              legend: {
                      display: false
              },
              scales: {
                  yAxes: [{
                      gridLines: {
                              display:false
                      },
                      ticks: {
                          beginAtZero:true
                      }
                  }],
                  xAxes: [{
                      gridLines: {
                              display:false
                      },
                      ticks: {
                          beginAtZero:true
                      }
                  }]
              }
          }
      };  

      handleGenerateGraph();
    };

  	interestItem = function(interest,value){
	    return{
	        interest:interest,
	        interestValue: value
	    }
	};

  	var handleGenerateGraph = function(){
  		if(topUserInterests!== undefined){
            topUserInterests.clear();
            topUserInterests.destroy();    
        }
       
  		var ctxInterest = document.getElementById("topUserInterests").getContext("2d");
  		topUserInterests = new Chart(ctxInterest, barChartData);
  	};

    createCompetingAppsBarGraph = function(appdata){
         
        var items = [0,0,0,0,0];
        appdata.forEach(function(item){
            if(item.ctr==0){
              items[0] = item.total;
            }
            else if(item.ctr==1){
              items[1] = item.total; 
            }
            else if(item.ctr==2){
              items[2] = item.total; 
            }
            else if(item.ctr==3){
              items[3] = item.total; 
            }
            else if(item.ctr>3){
              items[4] = items[4] + item.total; 
            }
        });
        //Calculate the users with zero apps.
        items[0] = totalActiveUsers - items[1]- items[2] - items[3] - items[4];

        // barChartDataCompetingApps = {
        //     labels : ['0','1','2','3','3+'],
        //     datasets : [
        //         {
        //             fillColor : semusiCommon.basicColors[0],
        //             data : items
        //         }
        //     ]
        // };
         
         
         barChartDataCompetingApps = {
              type: 'bar',
              data: {
                  labels: ['0','1','2','3','4','5','6','7','7+'],
                  datasets: [{
                      label: '',
                      data: items,
                      backgroundColor: [
                          'rgba(186, 222, 247, 8)',
                          'rgba(181, 226, 154, 25)',
                          'rgba(161, 232, 231, 23)',
                          'rgba(110, 121, 181, 7)',
                          'rgba(0, 196, 193, 42)',
                          'rgba(181, 226, 154, 25)',
                          'rgba(161, 232, 231, 23)',
                          'rgba(110, 121, 181, 7)',
                          'rgba(0, 196, 193, 42)'
                      ],
                      borderColor: [
                         'rgba(186, 222, 247, 8)',
                          'rgba(181, 226, 154, 25)',
                          'rgba(161, 232, 231, 23)',
                          'rgba(110, 121, 181, 7)',
                          'rgba(0, 196, 193, 42)',
                          'rgba(181, 226, 154, 25)',
                          'rgba(161, 232, 231, 23)',
                          'rgba(110, 121, 181, 7)',
                          'rgba(0, 196, 193, 42)'
                      ]
                  }]
              },
              options: {
                  legend: {
                      display: false
                  },
                  scales: {
                      yAxes: [{
                          gridLines: {
                              display:false
                          },
                          scaleLabel: {
                            display: true,
                            labelString: 'Number Of Users'
                          }
                      }],
                      xAxes: [{
                          gridLines: {
                              display:false
                          },
                          scaleLabel: {
                            display: true,
                            labelString: 'Number Of competing Apps'
                          }
                      }]
                  }
              }
          };

        generateCompetingAppGraph()
    }
    generateCompetingAppGraph = function(){
       
      if(competingAppUsers!== undefined){
            competingAppUsers.clear();
            competingAppUsers.destroy();    
        }
      var ctx = document.getElementById("chartCompetingUsers").getContext("2d");
      competingAppUsers = new Chart(ctx, barChartDataCompetingApps);
    }
  	//public methdods
  	semusiDemographics.Init = function(){
  		if(semusiCommon.ACTIVE_APP_ID == undefined || semusiCommon.ACTIVE_APP_ID==""){
   		window.location =  "/dashboard";

	      	return;
	    }
      handleChartJs();
  		semusiDemographics.getActiveUserInterests();	
  		semusiDemographics.getActiveUserDemographics();
      
  	};

  	semusiDemographics.getActiveUserInterests = function(){
      semusiDemographics.Interests = [];
      
      $.ajax({
          type:"GET",
          url:semusiCommon.API_PARTS.metrices.r + '/getActiveUserInterests',
          data:{
              api_key: semusiCommon.getActiveUser.api_key,
              uniqueNumber: semusiCommon.randomNumber(),
              app_id: semusiCommon.ACTIVE_APP_ID,
          },
          success:function (data) {
               
            data.forEach(function(item){
            if(typeof(item.total) === 'number'){
              semusiDemographics.Interests.push(new interestItem(item.interest,item.total));
            }
            
          });
              createBarChartData();
          },
          error: function(error){
             
            
          } 

           
      });
  	};

  	semusiDemographics.getActiveUserDemographics = function(){
      semusiDemographics.Interests = [];
      
      $.ajax({
          type:"GET",
          url:semusiCommon.API_PARTS.metrices.r + '/getActiveUserDemographics',
          data:{
              api_key: semusiCommon.getActiveUser.api_key,
              app_id: semusiCommon.ACTIVE_APP_ID,
              uniqueNumber: semusiCommon.randomNumber(),
          },
          success:function (data) {
              $("#overlay").hide();
              semusiDemographics.currenData=data;
              populateUsersByGender();
              semusiDemographics.getActiveUserCompetingAppStats();
          }
      });
  	};

    semusiDemographics.getActiveUserCompetingAppStats = function(){
      semusiDemographics.Interests = [];
      
      $.ajax({
          type:"GET",
          url:semusiCommon.API_PARTS.metrices.r + '/getActiveUserCompetingAppStats',
          data:{
              api_key: semusiCommon.getActiveUser.api_key,
              app_id: semusiCommon.ACTIVE_APP_ID,
              uniqueNumber: semusiCommon.randomNumber(),
          },
          success:function (data) {
              createCompetingAppsBarGraph(data);
          }
      });
    };
}(window.semusiDemographics = window.semusiDemographics || {}, jQuery));