// // // OBSERVERS // // $(function() { // // LOGIN PAGE OBSERVERS // if ($("#loginMainPage").doesExist()){ $('#forgotPwButton').click(function(ev){ $('#forgotPw').on('shown', function () { $("#forgotUsername").first().focus(); }); $('#forgotPw').modal('show'); return false; }); $('#registrerButton').click(function(ev){ $('#registrer').on('shown', function () { $("#brukernavn").first().focus(); }); $('#registrer').modal('show'); return false; }); $('#submitRegistrer').click(function(ev){ alert('Registrer NY bruker'); }); $('#loginButton').bind('click', function(){ auth_request(); return false; }); $('#submitPinSMS').bind('click', function(){ pin_request(); return false; }); $('#submitVerifyPinSMS').bind('click', function(){ verify_pin_request(); return false; }); $('#loginForm input').keyup(function(e) { // submit form on enter if (e.keyCode == '13'){ auth_request(); } }); $('#loginForm input').each(function(iter, e){ // auto focus the text box for username e.focus(); return false; // abort on first find }); function submit_forgot_pw(e){ $('#submitForgotPw').hide(); $('#forgotPw').find('.alert.alert-error').remove(); // remove errors if exists loader('#forgotPw', 'add', 50); $.get('/ajax/auth.php', $('#forgotForm').serialize(), function(response){ loader(null, 'remove'); if (response.status=='ok'){ $('#forgotPw > .modal-body').html(response.html); }else{ $('#submitForgotPw').show(); $('#forgotPw > .modal-body').prepend(response.html); } }, 'json'); return false; } // enter press on forgot pw $('#forgotUsername').keyup(function(e) { if (e.keyCode == '13'){ submit_forgot_pw(e); } }); // // observe the forgot password button // $('#submitForgotPw').click(submit_forgot_pw); } // // reset pw page // if ($("#resetpwPage").doesExist()){ $('#resetPWButton').bind('click', function(){ auth_request_reset(); return false; }); } // // observe the logout button // if ($('#logOutButton').doesExist()){ $('#logOutButton').click(function(){ $.get('/ajax/auth.php', {method:'logout'}, function(response){ if (response.status='ok'){ top.location.href=response.redir; }else{ // failsafe! top.location.href='/ajax/auth.php?method=logout'; } }, 'json'); return false; }); } // // RESPONSE SELECTOR OBSERVE // if ($("#responsSelect").doesExist()){ $('#responsSelect').change(function(e) { var newUrlQuery = query_params({id:e.currentTarget.value}); location.search = newUrlQuery; }); /*$('#clientSelectorReset').click(function(e) { e.preventDefault(); var newUrlQuery = query_params({c:$(e.currentTarget).data('id')}); location.search = newUrlQuery; });*/ } // // CLIENT SELECTOR OBSERVE // if ($("#clientSelector").doesExist()){ $('#clientSelector').change(function(e) { var newUrlQuery = query_params({c:e.currentTarget.value}); location.search = newUrlQuery; }); $('#clientSelectorReset').click(function(e) { e.preventDefault(); var newUrlQuery = query_params({c:$(e.currentTarget).data('id')}); location.search = newUrlQuery; }); } // // DATE PICKER OBSERVERS // if ($("#dateview-box").doesExist()){ // only execute if element exists on page // observe the date open selector $("#dateview-box").click(function(el) {toggle_date_box(this);}); // observe the date submit button $("#dateButton").click(function() { $('#dateAlert').hide(); toggle_date_box(); var dStart=$('#date-start').datepicker().data().date; var dEnd = $('#date-end').datepicker().data().date; // get prefix var prefix = $('#dateSelector').data('prefix'); var newUrlQuery = query_params({ds:dStart, de:dEnd}, prefix); location.search = newUrlQuery; }); if ($('#date-start') && $('#date-end')){ init_datePicker(); } } if ($("#dateview-box_nosub").doesExist()){ // only execute if element exists on page // observe the date open selector $("#dateview-box_nosub").click(function(el) {toggle_date_box(this);}); // observe the date submit button $("#dateButton").click(function() { $('#dateAlert').hide(); toggle_date_box(); var dStart=$('#date-start').datepicker().data().date; var dEnd = $('#date-end').datepicker().data().date; // get prefix var prefix = $('#dateSelector').data('prefix'); var newUrlQuery = query_params({ds:dStart, de:dEnd}, prefix); location.search = newUrlQuery; }); if ($('#date-start') && $('#date-end')){ init_datePicker_nosub(); } } // // SIDEBAR OBSERVERS // if ($(".sidebar").doesExist()){ $(".menu-enabler").on("click", function(event){ //$('.sidebar').toggleClass('show-sidebar'); $('.sidebar').toggleClass(function() { if ($(this).hasClass('show-sidebar')) { $(this).removeClass('show-sidebar'); $('.sidebar > div').removeClass('active'); $('.menu-enabler > span').addClass('icon-chevron-right'); $('.menu-enabler > span').removeClass('icon-chevron-left'); return ''; } else { $('.sidebar > div').addClass('active'); $('.menu-enabler > span').addClass('icon-chevron-left'); $('.menu-enabler > span').removeClass('icon-chevron-right'); return 'show-sidebar'; } }); return false; }); $(window).scroll(function (event) { position_sidebar(); }); $(window).resize(function (event) { position_sidebar(); }); position_sidebar(); // rposition the sidebar, acording to window size } // resize observe and set heigth of maincontainer set_container_height(); $(window).resize(function (event) { set_container_height(); }); // // Auto scroller when linked with an url hash, for smaller screens // var $hash = window.location.hash; if($hash) { if ($(window).width() <= 700){ if ($($hash).length != 0){ var $elTopPos = jQuery($hash).offset().top; jQuery('html, body').animate({scrollTop:$elTopPos}, 'slow'); //remove hash window.location.hash = ''; } } } // // INITIATE TOOLTIP // $("[rel=tooltip]").tooltip(); // // HighCharts locale and other default settings settings // if (typeof Highcharts !="undefined"){ Highcharts.setOptions({ global: { useUTC: true }, lang: { months: ['Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember'], weekdays: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'] } }); } // serach for click2show class init_click2show(); // // init dropdown lists // // observe the config buttons $('.dropdownList').each(function(index, element) { var userid = $(element).data('userid'); // observe delete button $(element).find('.dropdownListDelete').click(function(e){ e.preventDefault(); action_buttons('deleteUser', userid, "removeLine", ['Er du sikker på at du vil slette denne brukeren?', 'Avbryt', 'Slett bruker']); }); // observe deactivate button $(element).find('.dropdownListActivateToggle').click(function(e){ e.preventDefault(); action_buttons('clientActivateToggle', userid, "muteLine"); }); // observe deactivate kw button $(element).find('.dropdownListCwActivateToggle').click(function(e){ e.preventDefault(); action_buttons('codewordActivateToggle', userid, "muteLine"); }); }); }); // // function simple search filter // function simple_table_filter(searchBox, rowSelector, targetSeslector){ $(searchBox).delayInput(function(el){ var value = el.val(); $(rowSelector).each(function(index, row){ // skip header if (index!=0){ if (value=="") $(row).show(); else{ var curtext = $(row).find(targetSeslector).text().toLowerCase(); if (curtext.indexOf( value.toLowerCase() ) ==-1) $(row).hide(); else $(row).show(); } } }); },200).keypress(function (evt) { //Deterime where our character code is coming from within the event var charCode = evt.charCode || evt.keyCode; if (charCode == 13) { //Enter key's keycode return false; } });; } // // Dropdown config buttons helpers // function action_buttons(action, id, visualAction, confirmText){ createOverlay('listView'); var obj = {method:action, uid:id}; if (typeof confirmText !="undefined" && confirmText[0].length >=1){ bootbox.confirm({ message: confirmText[0], buttons: { 'cancel': { label: confirmText[1] }, 'confirm': { label: confirmText[2] } }, callback: function(r) { if (r === true) action_buttons_req(obj, visualAction); else removeOverlay('listView'); } }); }else{ action_buttons_req(obj, visualAction); } } function action_buttons_req(obj, visualAction){ simpleAjax(obj, "auth").done(function ( data ) { removeOverlay('listView'); if (data.status=="ok"){ //if (typeof data.msg != 'undefined'){ if (visualAction == "removeLine"){ $('#row_'+obj['uid']).find('td').css({background:'#f6dadb'}); setTimeout(function(){ $('#row_'+obj['uid']).addClass('fade').delay(500).queue(function( n ) {$(this).remove()}); }, 500); //bootbox.alert(data.msg, function() { //}); }else if (visualAction == "muteLine"){ var foundLabel = $('#row_'+obj['uid']).find('td.labelHolder'); var foundbutton = $('#row_'+obj['uid']).find('.dropdownListActivateToggle span'); var foundbutton_cw = $('#row_'+obj['uid']).find('.dropdownListCwActivateToggle span'); if (data.lineStatus == "active") { foundLabel.html('Aktiv'); foundbutton.text('Deaktiver'); foundbutton_cw.text('Deaktiver'); $('#row_'+obj['uid']).removeClass('muted'); }else { foundLabel.html('Deaktivert'); foundbutton.text('Aktiver'); foundbutton_cw.text('Aktiver'); $('#row_'+obj['uid']).addClass('muted'); } } //} return true; }else{ var msg = (typeof data.msg !="undefined")?data.msg:"Error, vennligst kontakt kundeservice hvis problemet vedvarer."; bootbox.alert(msg, function() {}); } }); return false; } // // function to show big info // function click2show(el, forceHeight, addClass){ var addedClass = (typeof addClass != "undefined")?addClass:""; var element = $(el); element.addClass('click2showHidden ' + addedClass); // get height of wrapped element if (typeof forceHeight !="undefined" && !isNaN(forceHeight)){ var elHeight = forceHeight; }else{ var elHeight = element.children(":first").height; } var container = $('

| ').addClass('dblist').html('Turnover').appendTo(tr); } else { $(' | ').addClass('dblist').html(element.name).appendTo(tr); } $(element.data).each(function(index2, d) { count += d[1]; }); if (element.name == "Turnover"){ billingTotal.find('span').html(number_format(count) +'.-'); $(' | ').html(number_format(count) +'.-').appendTo(tr); totalRevenue = count; }else{ $(' | ').html(number_format(count)).appendTo(tr);
							TotalSent += count;	
						}
						
						
					});
					
					billingSent.find('span').html(number_format(TotalSent));	
					
					var average = totalRevenue / TotalSent;
					
					billingAvr.find('span').html(number_format((average), 2) + '.-' );	
					
					// add the wrapper
					if (json.data.length > 3) {
						$(table).wrap( "");
						click2show('#BillingSummaryWrap');
					}
					
				}
			}
			
			/* Temporarly remove highcharts link, until production release */
			$('.highcharts-container svg:last-child > text').hide();
		
		}else{
			bootbox.alert({message: json.msg,buttons: {'ok': { label: "Lukk"}}});		
		}
	});
}
function gen_excel_rapport(fra_dato,til_dato,avsender,status,reload) {
  var $ret = simpleAjax({'method':'excel_rapport', fra_dato:fra_dato , til_dato:til_dato, avsender:avsender, status:status}, 'ajaxmq').done(function ( json ) {
    if (json.status=="ok"){ 
        //alert(fra_dato+avsender+status);
        if(reload==1) {
            location.reload();
        }
        else {
            bootbox.alert({message: json.msg,buttons: {'ok': { label: "Lukk"}}});
        }
    }
    else{
        bootbox.alert({message: json.msg,buttons: {'ok': { label: "Lukk"}}});
    }
  });       
}
function raw_bulk(element, ds, de){
		
		var $ret = simpleAjax({'method':'bulkRaw', ds:ds, de:de}, 'stats').done(function ( json ) {	
			
			if(json.status=="ok"){
				
				if (json.data != null){
			
					var App = {};
					
					App.mainCollection = new Backbone.Collection(json.data);
					bbGrid.setDict('no');
					
					var MyGrid = new bbGrid.View({  
						subgrid: true,
						subgridAccordion: false,          
						container: $(element),      
						collection: App.mainCollection,                                                
						colModel: [{ title: 'Date', name: 'dato', sortType:'number', index:true},
							   { title: 'Number', name: 'antall' , sortType:'number', index:true,actions:function(thisid){							    
								  var antall = App.mainCollection.get(thisid)['attributes']['antall'];	
								  return antall.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");			     
								}     
							   },							
                                                          ],                                                       
						onRowExpanded: function($el, rowid) {							
							
							var $selectedRow = App.mainCollection.get(rowid)['attributes']['dato'];
							
							//console.log($selectedRow);
							
							var _subCollection = Backbone.Collection.extend({
								url: 'ajax/stats.php?method=quickSubStat&d='+ $selectedRow
							});
							
							var subCollection = new _subCollection();					
							
							var fetchObj = subCollection.fetch({ success: function(o,coll){
								
								if (typeof coll['status'] !="undefined" &&  coll['status']=="failed") {
									alert(subCollection.models[0]['attributes']['msg']);
									
								}
														
							} });
							
							var subgrid = new bbGrid.View({
								autofetch:false,
								subgrid: true,
								subgridAccordion: false,       
								container: $el,
								collection: subCollection,
                                                                 buttons: [{
                                                                    'id': 'EksportDatoID',
                                                                    'title': 'Export all rows from '+$selectedRow+' to Excel',
                                                                    onClick: function(event){ 
                                                                        //var dato = $selectedRow;
                                                                        //var avsender = subCollection.get(thisid)['attributes']['avsender'];
                                                                        //alert('test2:'+dato);
                                                                        gen_excel_rapport($selectedRow,$selectedRow,'','');
                                                                    }
                                                                }],
								onBeforeRender: function(){},                                                                
								colModel: [{title:'Sender', name : 'avsender'}, 
									  {title:'Number', name : 'antall',actions:function(thisid){							    
									      var antall = subCollection.get(thisid)['attributes']['antall'];	
									      return antall.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");			     
									    } 
									  },                                                                                                                                                                                                            
                                                                        ],
								onRowExpanded: function($el2, rowid2) {
									//console.log(rowid2);
									var $sender = subCollection.get(rowid2)['attributes']['avsender'];																		
									var _subCollection2 = Backbone.Collection.extend({
										url: 'ajax/stats.php?method=quickSubStat&d=' + $selectedRow +'&s='+ encodeURIComponent($sender)
									});
									
									var subCollection2 = new _subCollection2();
									
									
									subCollection2.fetch({ success: function(){
										
										var ifNote = subCollection2.first().pick("note");
											
											if (typeof ifNote.note != "undefined"){
												
												$($el2).prepend(" "+ifNote.note+"");
											}
																		
									} });
									
									var subgrid2 = new bbGrid.View({
										autofetch:false,
										subgrid: true,
										subgridAccordion: false,       										
										rows: 100,
										container: $el2,
										collection: subCollection2,
										colModel: [{title:'ID', name : 'id', className:'hidden', index:true}, 
											   {title:'Avsender', name : 'avsender', className:'hidden', index:true}, 													
											   {title:'Status', name : 'status' ,filter: true, filterColName: 'status', index: true, actions:function(thisid){
												var color = 'label-warning';
												var thisStatus = subCollection2.get(thisid)['attributes']['status'];										
													if (thisStatus == "delivered") color = 'label-success';
													else if (thisStatus == "failed") color = 'label-important';
													return ""+thisStatus+""}
											    },
											    {title:'Number', name : 'antall',actions:function(thisid){							    
												 var antall = subCollection2.get(thisid)['attributes']['antall'];	
												 return antall.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");			     
											      } 														
											    }                                                                                          
                                                                                          ],
                                                                                buttons: [{
                                                                                    'id': 'EksportDatoAvsenderID',
                                                                                    'title': 'Export all rows from '+$selectedRow+' with sender "'+$sender+'" to Excel',
                                                                                    onClick: function(event){                                                                                                                                                                         
                                                                                        gen_excel_rapport($selectedRow,$selectedRow,$sender,'');
                                                                                    }
                                                                                }],
										onReady: function(){
											
											$('.gridShowFullMessage').unbind().click(function(e){
													e.preventDefault();
													var el = e.currentTarget;
													
													simpleAjax({'method':'quickStatMessage', id:$(el).data('id'), db:'bulk'}, 'stats').done(function ( json ) {	
															//console.log('counter');
															bootbox.alert(json.data.melding);
													});
													
											});
                                                                                        
                                                                                       
											
										},
										onRowExpanded: function($el3, rowid3) {
										  //console.log(rowid2);
										  var $status = subCollection2.get(rowid3)['attributes']['status'];
										  var $sender = subCollection2.get(rowid3)['attributes']['avsender'];
										  var _subCollection3 = Backbone.Collection.extend({
										  url: 'ajax/stats.php?method=quickSubStat&d=' + $selectedRow +'&status='+ encodeURIComponent($status)+'&s='+ encodeURIComponent($sender)
										});	
									
										var subCollection3 = new _subCollection3();																		
										subCollection3.fetch({ success: function(){
										
										var ifNote = subCollection3.first().pick("note");
											
											if (typeof ifNote.note != "undefined"){
												
												$($el3).prepend(" "+ifNote.note+"");
											}
																		
										}			  
										});
										var subgrid3 = new bbGrid.View({
										autofetch:false,
										rows: 100,
										container: $el3,
										collection: subCollection3,
										colModel: [{title:'ID', name : 'id', className:'hidden-phone', index:true}, 
													{title:'Time', name : 'tid_ut', sortType:'number', index:true},
													{title:'Country code', name : 'land', index:true, className:'hidden-phone'},  
													{title:'GSM', name : 'gsm'}, 
													{title:'Operator', name : 'operator'}, 													
													{title:'Parts', name : 'deler'}, 
													{title:'Message', name : 'melding', className:'hidden-phone', actions:function(thisid){
														var message = subCollection3.get(thisid)['attributes']['melding'];
														
														if (typeof message != "undefined") return ""+message+"..."
														else return '';
														}
													}],
                                                                                buttons: [{
                                                                                    'id': 'EksportDatoAvsenderStatusID',
                                                                                    'title': 'Export all rows from '+$selectedRow+' with sender "'+$sender+'" and status "'+$status+'" to Excel',
                                                                                    onClick: function(event){                                                                                                                                                                         
                                                                                        gen_excel_rapport($selectedRow,$selectedRow,$sender,$status);
                                                                                    }
                                                                                }],
										onReady: function(){
											
											$('.gridShowFullMessage').unbind().click(function(e){
													e.preventDefault();
													var el = e.currentTarget;
													
													simpleAjax({'method':'quickStatMessage', id:$(el).data('id'), db:'bulk'}, 'stats').done(function ( json ) {	
															//console.log('counter');
															bootbox.alert(json.data.melding);
													});
													
											});	
											
										}
										
										
									});							
								    }
								
								
									});
								}
							});
						}
					});
				}
				else{
					
					// nothing to get
					
					$('#bulkContainerRaw').html(' No data for this customer.');
						
					
				}
			}
		});				
}
function raw_push(element, ds, de, country){
		
	if (typeof country=="undefined") country = 47;
					
	var $ret = simpleAjax({'method':'pushRaw', ds:ds, de:de, c:country}, 'stats').done(function ( json ) {	
	    if(json.status=="ok"){
				
		if (json.data != null){
			    // empty contents to update fresh when a country is changed
			    $(element).html('');
			
			    var App = {};			
			    App.mainCollection = new Backbone.Collection(json.data);
			    bbGrid.setDict('no');
			
			    var MyGrid = new bbGrid.View({  
				subgrid: true,
				subgridAccordion: false,          
				container: $(element),      
				collection: App.mainCollection,
				colModel: [{title:'ID', name : 'id', className:'hidden'},
					   { title: 'Date', name: 'dato', sortType:'number', index:true},
					   { title: 'Number', name: 'antall' , sortType:'number', index:true},
					   { title: 'Tried', name: 'pris' , sortType:'number', index:true},
					   { title: 'Turnover', name: 'delivered_pris' , sortType:'number', index:true},
					   { title: 'Success rate', name: 'success_rate' , sortType:'number', className:'color', index:true,
								actions:function(thisid){
									var value = App.mainCollection.get(thisid)['attributes']['success_rate'];
									var num = value.split(',');									
									var $col = '#498351';
									
									if (num[0] <= 50){
										
										$col = '#a96c66';
									
									}else if (num[0] <= 70){
										
										$col = '#a99a66';
										
									}else if (num[0] <= 90){
										
										$col = '#5aa063';
									
									}else if (num[0] < 100){	
									
										$col = '#498351';
									}
									
									$($(this.$el)).find('.color').css({background:$col});
									return ' '+value+'';
									
								}
							}],
				onRowExpanded: function($el, rowid) {
					
					var $selectedRow = App.mainCollection.get(rowid)['attributes']['dato'];															
					var _subCollection = Backbone.Collection.extend({
						url: 'ajax/stats.php?method=quickSubStatPush&d='+ $selectedRow +'&c='+ country
					});
					
					var subCollection = new _subCollection();					
					
					var subgrid = new bbGrid.View({
						autofetch:true,     
						container: $el,
						subgrid: true,
						subgridAccordion: false,          
						rows:100,
						collection: subCollection,
						onBeforeRender: function(){							
							//console.log(subCollection.models[0]['attributes']['status']);
							subgrid.dict.noData = "Ingen data å vise. ";
							if (typeof subCollection.models[0] !="undefined" && subCollection.models[0]['attributes']['status']=="failed") {
								alert(subCollection.models[0]['attributes']['msg']);
								return false;
							}
						},
						colModel: [{title:'ID', name : 'id', className:'hidden', index:true},
							   {title:'Keyword', name : 'kode', className:'hidden-phone', index:true}, 
							   {title:'Price', name : 'pris', index:true, className:'hidden-phone'},
							   {title:'Shortnumber', name : 'kortnr'},							   
							   {title:'Status', name : 'dlrstatus' ,filter: true, filterColName: 'dlrstatus', index: true,actions:function(thisid){								
                                                                var color = 'label-warning';
                                                                var thisStatus = subCollection.get(thisid)['attributes']['dlrstatus'];
                                                                
                                                                if (thisStatus == "delivered") color = 'label-success';
                                                                else if (thisStatus == "failed") color = 'label-important';
                                                                
                                                                return ""+thisStatus+""}
							   },
							  {title:'Number', name : 'antall'},							   						  
							 ],
						onReady: function(){
							
						},
				   		onRowExpanded: function($el2, rowid2) {
						       console.log(rowid2);
							var $status = subCollection.get(rowid2)['attributes']['dlrstatus'];
							var $tjid = subCollection.get(rowid2)['attributes']['tjeneste_id'];
							var $pris = subCollection.get(rowid2)['attributes']['pris'];
										  var _subCollection2 = Backbone.Collection.extend({
										  url: 'ajax/stats.php?method=quickSubStatPush&d=' + $selectedRow +'&status='+ encodeURIComponent($status)+'&tjid='+ encodeURIComponent($tjid)+'&pris='+encodeURIComponent($pris)
										});	
									
										var subCollection2 = new _subCollection2();
										subCollection2.fetch({ success: function(){
										
										var ifNote = subCollection2.first().pick("note");
											
											if (typeof ifNote.note != "undefined"){
												
												$($el2).prepend(" "+ifNote.note+"");
											}
																		
										}			  
										});
										var subgrid2 = new bbGrid.View({
										autofetch:false,
										rows: 100,
										container: $el2,
										collection: subCollection2,
										colModel: [{title:'Id', name : 'id', className:'hidden-phone', index:true}, 
													{title:'Time', name : 'tid_ut', sortType:'number', index:true},													
													{title:'Gsm', name : 'gsm'},
													{title:'Operator', name : 'operator'},
													{title:'Message', name : 'melding', className:'hidden-phone', actions:function(thisid){
														var message = subCollection2.get(thisid)['attributes']['melding'];
														
														if (typeof message != "undefined") return ""+message+"..."
														else return '';
														}
													}],
										onReady: function(){
											
											$('.gridShowFullMessage').unbind().click(function(e){
													e.preventDefault();
													var el = e.currentTarget;
													
													simpleAjax({'method':'quickStatMessage', id:$(el).data('id'), db:'push'}, 'stats').done(function ( json ) {	
															//console.log('counter');
															bootbox.alert(json.data.melding);
													});
													
											});	
											
										}
										
										
									});							
								    }
						
					});
					
				}
			});
		}
		else{
		  // nothing to get
		  $('#pushContainerRaw').html(' No data for this customer');							
		}
	    }
	});
		
}
function pushCodeWords(element, ds, de, country){
		
		if (typeof country=="undefined") country = 47;
					
		var $ret = simpleAjax({'method':'pushCodeWords', ds:ds, de:de, c:country}, 'stats').done(function ( json ) {	
			//console.log(json);
			// empty contents to update fresh when a country is changed
			$(element).html('');
			
			var App = {};
			var totalt=0;
			App.mainCollection = new Backbone.Collection(json.data);
			bbGrid.setDict('no');
			
			var MyGrid = new bbGrid.View({  
				subgrid: true,
				subgridAccordion: false,          
				container: $(element),      
				collection: App.mainCollection,
				colModel: [{title:'ID', name : 'id', className:'hidden'},
					   {title:'Tjeneste ID', name : 'tjeneste_id',className:'hidden'},
					   {title:'Eier ID', name : 'eier_id',className:'hidden'},
					   {title:'Keyword', name : 'kode', sortType:'string', index:true,actions:function(thisid){							
							//console.log('ID: '+thisid);
                                                        var thiskode = App.mainCollection.get(thisid)['attributes']['kode'];                                                                
                                                        if (thiskode == "ÅÅÅ") return 'TOTALT'
							else return thiskode; 
						    }					     					     
					  }, 
					   {title:'Customer', name : 'kunde', index:true, className:'hidden-phone'},
					   {title:'Price', name : 'pris', index:true, className:'hidden-phone'},
					   {title:'Shortnumber', name : 'kortnr'},							   					   
					   {title:'Number', name : 'antall', sortType:'number', index:true,actions:function(thisid){							
							//console.log('ID: '+thisid);
                                                        var antall = App.mainCollection.get(thisid)['attributes']['antall'];
							//console.log('ID: '+thisid+' Antall:'+antall);							
							if (antall == "TOTAL") {							  
							  return ''+totalt+'';
							}
							else {
							  totalt = +antall+ +totalt;
							  return antall; 
							}											     					     					     
						    }
					  
					   }],
				onRowExpanded: function($el, rowid) {
					
					var $tjid = App.mainCollection.get(rowid)['attributes']['tjeneste_id'];
					var $eierid = App.mainCollection.get(rowid)['attributes']['eier_id'];
					var $pris = App.mainCollection.get(rowid)['attributes']['pris'];
					
					//var $selectedCountry = $('#countrySelector').find('select').val();
					
					if($tjid>0 && $eierid>0) {
					  var _subCollection = Backbone.Collection.extend({
						url: 'ajax/stats.php?method=pushGroupStatus&tjid='+ $tjid +'&eier='+ $eierid +'&pris='+ $pris
					  });
					
					  var subCollection = new _subCollection();										
					
					  var subgrid = new bbGrid.View({
						autofetch:true,
						subgrid: true,
						subgridAccordion: false,
						container: $el,
						rows:100,
						collection: subCollection,
						onBeforeRender: function(){
							
							//console.log(subCollection.models[0]['attributes']['status']);
							subgrid.dict.noData = "Ingen data å vise. ";
							if (typeof subCollection.models[0] !="undefined" && subCollection.models[0]['attributes']['status']=="failed") {
								alert(subCollection.models[0]['attributes']['msg']);
								return false;
							}
						},
						colModel: [
						   { title: 'Id', name: 'id',className:'hidden'},
						   {title:'Tjeneste ID', name : 'tjeneste_id',className:'hidden'},
						   { title: 'eier', name: 'eier_id', className:'hidden'},
						   { title: 'Number', name: 'antall' , sortType:'number', index:true},
						   {title:'Status', name : 'dlrstatus' ,filter: true, filterColName: 'dlrstatus', index: true,actions:function(thisid){							
							var color = 'label-warning';
                                                        var thisStatus = subCollection.get(thisid)['attributes']['dlrstatus'];                                                                
                                                        if (thisStatus == "delivered") color = 'label-success';
                                                        else if (thisStatus == "failed") color = 'label-important';                                                                
                                                        return ""+thisStatus+""}						     
						    }
						   ],
                        onRowExpanded: function($el2, rowid2) {
                                                  
                                                  var $tjid = subCollection.get(rowid2)['attributes']['tjeneste_id'];
                                                  var $eierid = subCollection.get(rowid2)['attributes']['eier_id'];
                                                  var $status = subCollection.get(rowid2)['attributes']['dlrstatus'];
                                                  
                                                  //var $selectedCountry = $('#countrySelector').find('select').val();
                                                  
                                                  
                                                  var _subCollection2 = Backbone.Collection.extend({
                                                                                                  url: 'ajax/stats.php?method=pushDaysCodeWord&tjid='+ $tjid +'&eier='+ $eierid +'&status='+ $status+'&pris='+ $pris
                                                                                                  });
                                                  
                                                  var subCollection2 = new _subCollection2();
                                                  
                                                  var subgrid2 = new bbGrid.View({
                                                                                autofetch:true,
                                                                                container: $el2,
                                                                                rows:100,
                                                                                collection: subCollection2,
                                                                                onBeforeRender: function(){
                                                                                
                                                                                //console.log(subCollection.models[0]['attributes']['status']);
                                                                                subgrid.dict.noData = "Ingen data å vise. Hvis du forsøker å hente detaljer for dato tidligere enn 1 November 2014, har dette blitt arkivert da vi flyttet over til nye KUNDEWEB. Ønsker du å få en detaljert rapport for en tidligere dato ta kontakt med oss og vi vil ta et manuellt søk for deg.";
                                                                                
                                                                                if (typeof subCollection2.models[0] !="undefined" && subCollection2.models[0]['attributes']['status']=="failed") {
                                                                                alert(subCollection2.models[0]['attributes']['msg']);
                                                                                return false;
                                                                                }
                                                                                },
                                                                                colModel: [
                                                                                           { title: 'Id', name: 'id',className:'hidden'},
                                                                                           { title: 'Date', name: 'dato', sortType:'number', index:true},
                                                                                           { title: 'Number', name: 'antall' , sortType:'number', index:true}
                                                                                           ],
                                                                                onReady: function(){
                                                                                
                                                                                }
                                                                                
                                                                                });
                                                  
                        } // SUBGRID2 slutt
						
					});
					}
				}
			});
		});
		
}
function bulkCodewords(element, ds, de, country){
		
		if (typeof country=="undefined") country = 47;
					
		var $ret = simpleAjax({'method':'bulkCodeWords', ds:ds, de:de, c:country}, 'stats').done(function ( json ) {	
			//console.log(json);
			// empty contents to update fresh when a country is changed
			$(element).html('');
			
			var App = {};
			var totalt=0;
			
			App.mainCollection = new Backbone.Collection(json.data);
			bbGrid.setDict('no');
			
			var MyGrid = new bbGrid.View({  
				subgrid: false,
				subgridAccordion: false,          
				container: $(element),      
				collection: App.mainCollection,
				colModel: [{title:'ID', name : 'id', className:'hidden'},
					   {title:'Tjeneste ID', name : 'tjeneste_id',className:'hidden'},
					   {title:'Keyword', name : 'kode', sortType:'string', index:true,actions:function(thisid){														
                                                        var thiskode = App.mainCollection.get(thisid)['attributes']['kode'];                                                                
                                                        if (thiskode == "ÅÅÅ") return 'TOTALT';
							else return thiskode; 
						    }					     					     
					  },
					   {title:'Customer', name : 'kunde', sortType:'string', index:true},
					   {title:'Number', name : 'antall', sortType:'number', index:true,actions:function(thisid){							
							//console.log('ID: '+thisid);
                                                        var antall = App.mainCollection.get(thisid)['attributes']['antall'];
							//console.log('ID: '+thisid+' Antall:'+antall);							
							if (antall == "TOTAL") {							  
							  return ''+totalt.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ")+'';
							}
							else {
							  totalt = +antall+ +totalt;
							  return antall.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ");
							}							
						    }					     										     					     					     
					   }],
				onRowExpanded: function($el, rowid) {									
					
				}
			});
		});
		
}
function bulkUsers(element, ds, de, country){
		
		if (typeof country=="undefined") country = 47;
					
		var $ret = simpleAjax({'method':'bulkUsers', ds:ds, de:de, c:country}, 'stats').done(function ( json ) {	
			//console.log(json);
			// empty contents to update fresh when a country is changed
			$(element).html('');
			
			var App = {};
			var totalt=0;
			
			App.mainCollection = new Backbone.Collection(json.data);
			bbGrid.setDict('no');
			
			var MyGrid = new bbGrid.View({  
				subgrid: false,
				subgridAccordion: false,          
				container: $(element),      
				collection: App.mainCollection,
				colModel: [{title:'ID', name : 'id', className:'hidden'},					   
					   {title:'User', name : 'bruker', sortType:'string', index:true },					   
					   {title:'Number', name : 'antall', sortType:'number', index:true},
					   {title:'Country', name : 'land', sortType:'string', index:true}
					   ],
				onRowExpanded: function($el, rowid) {
				  
				}
			});
		});
		
}
function chart_bulk(element, ds, de, showButton, height){
	
	createOverlay(element.substr(1));
	
	if (typeof height != "number") var height = 200; 
	
	if (typeof showButton == "undefined") var showButton = false;
	
	var $ret = simpleAjax({'method':'bulkStat', ds:ds, de:de}, 'stats').done(function ( json ) {
		
		removeOverlay(element.substr(1));
				
		if (json.status=="ok"){
			
			$(' ').addClass('row-fluid headNumbers').html(' Sent during the period'+number_format(json.senttotal)+' ').appendTo(element);
				var listCont = $(' ').appendTo(element);
				
				if (showButton == true){
					var buttonCont = $(' ').addClass('btnCont').appendTo(element);
					$('').click(function(){top.location.href='?page=stats&sub=bulk'}).appendTo(buttonCont);
				}
				
				$('#bulkContainer button').show();
				
				chart.highcharts({
					chart: {
						renderTo: 'bulkChart',
						type: 'line',
						animation: false,
						height : height,
						zoomType: 'x',
						resetZoomButton: {
							theme: {
								fill: '#F5F5F5',
								stroke: '#B3B3B3',
								r: 4,
								states: {
									hover: {
										fill: '#E6E6E6',
										stroke: '#B3B3B3',
										
									}
								}
							}
						}
					},
					legend: {
            			maxHeight:60
					},
					/*title: {
						text: json.title
					},*/
					title: false,
					subtitle: {
						text: ''
					},
					plotOptions: {
						line: {
							marker: {
								enabled: false
							}
						},
						series:{
							
							shadow: false,
							animation:true	
							
						}
					},
					xAxis: {
						type: 'datetime'/*,
						title: {
							text: 'Dato'
						}*/
						
					},
					yAxis: {
						title: false,
						min: 0
					},
					tooltip: {
						shared: true
					},
					
					series: json.data
				});
			}
				
			
			// list only if there are several lines
			if (json.data.length > 1){  
			 
				$(' Summary').appendTo(listCont); var table = $('
 |