/*
* Document : controllers.js
* Author : pixelcave
* Description: Our example controllers for demo pages
*
*/
// Dashboard Content Controller
App.controller('DashboardCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
/*
* Init Chart.js Chart, for more examples you can check out http://www.chartjs.org/docs
*/
// Get Chart Container
var dashChartLinesCon = jQuery('.js-dash-chartjs-lines')[0].getContext('2d');
// Set Chart and Chart Data variables
var dashChartLines, dashChartLinesData;
// Lines Chart Data
var dashChartLinesData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'This Week',
fillColor: 'rgba(44, 52, 63, .07)',
strokeColor: 'rgba(44, 52, 63, .25)',
pointColor: 'rgba(44, 52, 63, .25)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(44, 52, 63, 1)',
data: [34, 42, 40, 65, 48, 56, 80]
},
{
label: 'Last Week',
fillColor: 'rgba(44, 52, 63, .1)',
strokeColor: 'rgba(44, 52, 63, .55)',
pointColor: 'rgba(44, 52, 63, .55)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(44, 52, 63, 1)',
data: [18, 19, 20, 35, 23, 28, 50]
}
]
};
// Init Lines Chart
dashChartLines = new Chart(dashChartLinesCon).Line(dashChartLinesData, {
scaleFontFamily: "'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif",
scaleFontColor: '#999',
scaleFontStyle: '600',
tooltipTitleFontFamily: "'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif",
tooltipCornerRadius: 3,
maintainAspectRatio: false,
responsive: true
});
}
]);
// UI Elements Activity Controller
App.controller('UiActivityCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Preview page loader
$scope.previewPageLoader = function () {
$scope.helpers.uiLoader('show');
setTimeout(function () {
$scope.helpers.uiLoader('hide');
}, 3000);
};
// Randomize progress bars values
var barsRandomize = function(){
jQuery('.js-bar-randomize').on('click', function(){
jQuery(this)
.parents('.block')
.find('.progress-bar')
.each(function() {
var el = jQuery(this);
var random = Math.floor((Math.random() * 91) + 10) + '%';
el.css('width', random);
if ( ! el.parent().hasClass('progress-mini')) {
el.html(random);
}
});
});
};
// SweetAlert, for more examples you can check out https://github.com/t4t5/sweetalert
var sweetAlert = function(){
// Init a simple alert on button click
jQuery('.js-swal-alert').on('click', function(){
swal('Hi, this is a simple alert!');
});
// Init an success alert on button click
jQuery('.js-swal-success').on('click', function(){
swal('Success', 'Everything updated perfectly!', 'success');
});
// Init an error alert on button click
jQuery('.js-swal-error').on('click', function(){
swal('Oops...', 'Something went wrong!', 'error');
});
// Init an example confirm alert on button click
jQuery('.js-swal-confirm').on('click', function(){
swal({
title: 'Are you sure?',
text: 'You will not be able to recover this imaginary file!',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#d26a5c',
confirmButtonText: 'Yes, delete it!',
closeOnConfirm: false,
html: false
}, function () {
swal('Deleted!', 'Your imaginary file has been deleted.', 'success');
});
});
};
// Init randomize bar values
barsRandomize();
// Init SweetAlert
sweetAlert();
}
]);
// UI Elements Chat Controller
App.controller('UiChatCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Helper variables - set in initChat()
var lWindow, lHeader, lFooter, cContainer, cHead, cTalk, cPeople, cform, cTimeout;
// Init chat
var initChat = function() {
// Set variables
lWindow = jQuery(window);
lHeader = jQuery('#header-navbar');
lFooter = jQuery('#page-footer');
cContainer = jQuery('.js-chat-container');
cHead = jQuery('.js-chat-head');
cTalk = jQuery('.js-chat-talk');
cPeople = jQuery('.js-chat-people');
cform = jQuery('.js-chat-form');
// Chat layout mode
switch (cContainer.data('chat-mode')) {
case 'full':
// Init chat windows' height
initChatWindows();
// ..also on browser resize or orientation change
jQuery(window).on('resize orientationchange', function(){
clearTimeout(cTimeout);
cTimeout = setTimeout(function(){
initChatWindows();
}, 150);
});
break;
case 'fixed':
// Init chat windows' height with a specific height
initChatWindows(cContainer.data('chat-height'));
break;
case 'popup':
// Init chat windows' height with a specific height
initChatWindows(cContainer.data('chat-height'));
// Adjust chat container
cContainer.css({
'position': 'fixed',
'right': '10px',
'bottom': 0,
'display': 'inline-block',
'padding': 0,
'width': '70%',
'max-width': '420px',
'min-width': '300px',
'z-index': '1031'
});
break;
default:
return false;
}
// Enable scroll lock to chat talk window
cTalk.scrollLock();
// Init form submission
cform.on('submit', function(e){
// Stop form submission
e.preventDefault();
// Get chat input
var chatInput = jQuery('.js-chat-input', jQuery(this));
// Add message
chatAddMessage(chatInput.data('target-chat-id'), chatInput.val(), 'self', chatInput);
});
};
// Init chat windows' height
var initChatWindows = function(customHeight) {
if (customHeight) {
cHeight = customHeight;
} else {
// Calculate height
var cHeight = lWindow.height() -
lHeader.outerHeight() -
lFooter.outerHeight() -
cHead.outerHeight() -
(parseInt(cContainer.css('padding-top')) + parseInt(cContainer.css('padding-bottom')));
// Add a minimum height
if (cHeight < 200) {
cHeight = 200;
}
}
// Set height to chat windows (+ people window if exists)
if (cPeople) {
cPeople.css('height', cHeight);
}
cTalk.css('height', cHeight - cform.outerHeight());
};
// Add a message to a chat window
var chatAddMessage = function(chatId, chatMsg, chatMsgLevel, chatInput) {
// Get chat window
var chatWindow = jQuery('.js-chat-talk[data-chat-id="' + chatId + '"]');
// If message and chat window exists
if (chatMsg && chatWindow.length) {
var chatBlockClasses = 'animated fadeIn push-50-l';
var chatMsgClasses = 'bg-gray-lighter';
// Post it to its related window (if message level is 'self', make it stand out)
if (chatMsgLevel === 'self') {
chatBlockClasses = 'animated fadeInUp push-50-r';
chatMsgClasses = 'bg-gray-light';
}
chatWindow.append('
'
+ '
'
+ jQuery('
').text(chatMsg).html()
+ '
'
+ '
');
// Scroll the message list to the bottom
chatWindow.animate({ scrollTop: chatWindow[0].scrollHeight }, 150);
// If input is set, reset it
if (chatInput) {
chatInput.val('');
}
}
};
// Init chat
initChat();
// Add Message
$scope.addMessage = function(chatId, chatMsg, chatMsgLevel) {
chatAddMessage(chatId, chatMsg, chatMsgLevel, false);
};
}
]);
// Forms Pickers and More Controller
App.controller('FormsPickersMoreCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Init jQuery AutoComplete example, for more examples you can check out https://github.com/Pixabay/jQuery-autoComplete
var initAutoComplete = function(){
// Init autocomplete functionality
jQuery('.js-autocomplete').autoComplete({
minChars: 1,
source: function(term, suggest){
term = term.toLowerCase();
var countriesList = ['Afghanistan','Albania','Algeria','Andorra','Angola','Anguilla','Antigua & Barbuda','Argentina','Armenia','Aruba','Australia','Austria','Azerbaijan','Bahamas','Bahrain','Bangladesh','Barbados','Belarus','Belgium','Belize','Benin','Bermuda','Bhutan','Bolivia','Bosnia & Herzegovina','Botswana','Brazil','British Virgin Islands','Brunei','Bulgaria','Burkina Faso','Burundi','Cambodia','Cameroon','Cape Verde','Cayman Islands','Chad','Chile','China','Colombia','Congo','Cook Islands','Costa Rica','Cote D Ivoire','Croatia','Cruise Ship','Cuba','Cyprus','Czech Republic','Denmark','Djibouti','Dominica','Dominican Republic','Ecuador','Egypt','El Salvador','Equatorial Guinea','Estonia','Ethiopia','Falkland Islands','Faroe Islands','Fiji','Finland','France','French Polynesia','French West Indies','Gabon','Gambia','Georgia','Germany','Ghana','Gibraltar','Greece','Greenland','Grenada','Guam','Guatemala','Guernsey','Guinea','Guinea Bissau','Guyana','Haiti','Honduras','Hong Kong','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Isle of Man','Israel','Italy','Jamaica','Japan','Jersey','Jordan','Kazakhstan','Kenya','Kuwait','Kyrgyz Republic','Laos','Latvia','Lebanon','Lesotho','Liberia','Libya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Madagascar','Malawi','Malaysia','Maldives','Mali','Malta','Mauritania','Mauritius','Mexico','Moldova','Monaco','Mongolia','Montenegro','Montserrat','Morocco','Mozambique','Namibia','Nepal','Netherlands','Netherlands Antilles','New Caledonia','New Zealand','Nicaragua','Niger','Nigeria','Norway','Oman','Pakistan','Palestine','Panama','Papua New Guinea','Paraguay','Peru','Philippines','Poland','Portugal','Puerto Rico','Qatar','Reunion','Romania','Russia','Rwanda','Saint Pierre & Miquelon','Samoa','San Marino','Satellite','Saudi Arabia','Senegal','Serbia','Seychelles','Sierra Leone','Singapore','Slovakia','Slovenia','South Africa','South Korea','Spain','Sri Lanka','St Kitts & Nevis','St Lucia','St Vincent','St. Lucia','Sudan','Suriname','Swaziland','Sweden','Switzerland','Syria','Taiwan','Tajikistan','Tanzania','Thailand','Timor L\'Este','Togo','Tonga','Trinidad & Tobago','Tunisia','Turkey','Turkmenistan','Turks & Caicos','Uganda','Ukraine','United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan','Venezuela','Vietnam','Virgin Islands (US)','Yemen','Zambia','Zimbabwe'];
var suggestions = [];
for (i = 0; i < countriesList.length; i++) {
if (~ countriesList[i].toLowerCase().indexOf(term)) suggestions.push(countriesList[i]);
}
suggest(suggestions);
}
});
};
// Init jQuery AutoComplete example
initAutoComplete();
}
]);
// Form Editors Controller
App.controller('FormsEditorsCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Disable auto init when contenteditable property is set to true
CKEDITOR.disableAutoInline = true;
// Init inline text editor
if (jQuery('#js-ckeditor-inline').length) {
CKEDITOR.inline('js-ckeditor-inline');
}
// Init full text editor
if (jQuery('#js-ckeditor').length) {
CKEDITOR.replace('js-ckeditor');
}
}
]);
// Forms Validation Controller
App.controller('FormsValidationCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Init Bootstrap Forms Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
var initValidationBootstrap = function(){
jQuery('.js-validation-bootstrap').validate({
ignore: [],
errorClass: 'help-block animated fadeInDown',
errorElement: 'div',
errorPlacement: function(error, e) {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: function(e) {
var elem = jQuery(e);
elem.closest('.form-group').removeClass('has-error').addClass('has-error');
elem.closest('.help-block').remove();
},
success: function(e) {
var elem = jQuery(e);
elem.closest('.form-group').removeClass('has-error');
elem.closest('.help-block').remove();
},
rules: {
'val-username': {
required: true,
minlength: 3
},
'val-email': {
required: true,
email: true
},
'val-password': {
required: true,
minlength: 5
},
'val-confirm-password': {
required: true,
equalTo: '#val-password'
},
'val-select2': {
required: true
},
'val-select2-multiple': {
required: true,
minlength: 2
},
'val-suggestions': {
required: true,
minlength: 5
},
'val-skill': {
required: true
},
'val-currency': {
required: true,
currency: ['$', true]
},
'val-website': {
required: true,
url: true
},
'val-phoneus': {
required: true,
phoneUS: true
},
'val-digits': {
required: true,
digits: true
},
'val-number': {
required: true,
number: true
},
'val-range': {
required: true,
range: [1, 5]
},
'val-terms': {
required: true
}
},
messages: {
'val-username': {
required: 'Please enter a username',
minlength: 'Your username must consist of at least 3 characters'
},
'val-email': 'Please enter a valid email address',
'val-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
},
'val-confirm-password': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long',
equalTo: 'Please enter the same password as above'
},
'val-select2': 'Please select a value!',
'val-select2-multiple': 'Please select at least 2 values!',
'val-suggestions': 'What can we do to become better?',
'val-skill': 'Please select a skill!',
'val-currency': 'Please enter a price!',
'val-website': 'Please enter your website!',
'val-phoneus': 'Please enter a US phone!',
'val-digits': 'Please enter only digits!',
'val-number': 'Please enter a number!',
'val-range': 'Please enter a number between 1 and 5!',
'val-terms': 'You must agree to the service terms!'
}
});
};
// Init Material Forms Validation, for more examples you can check out https://github.com/jzaefferer/jquery-validation
var initValidationMaterial = function(){
jQuery('.js-validation-material').validate({
ignore: [],
errorClass: 'help-block text-right animated fadeInDown',
errorElement: 'div',
errorPlacement: function(error, e) {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: function(e) {
var elem = jQuery(e);
elem.closest('.form-group').removeClass('has-error').addClass('has-error');
elem.closest('.help-block').remove();
},
success: function(e) {
var elem = jQuery(e);
elem.closest('.form-group').removeClass('has-error');
elem.closest('.help-block').remove();
},
rules: {
'val-username2': {
required: true,
minlength: 3
},
'val-email2': {
required: true,
email: true
},
'val-password2': {
required: true,
minlength: 5
},
'val-confirm-password2': {
required: true,
equalTo: '#val-password2'
},
'val-select22': {
required: true
},
'val-select2-multiple2': {
required: true,
minlength: 2
},
'val-suggestions2': {
required: true,
minlength: 5
},
'val-skill2': {
required: true
},
'val-currency2': {
required: true,
currency: ['$', true]
},
'val-website2': {
required: true,
url: true
},
'val-phoneus2': {
required: true,
phoneUS: true
},
'val-digits2': {
required: true,
digits: true
},
'val-number2': {
required: true,
number: true
},
'val-range2': {
required: true,
range: [1, 5]
},
'val-terms2': {
required: true
}
},
messages: {
'val-username2': {
required: 'Please enter a username',
minlength: 'Your username must consist of at least 3 characters'
},
'val-email2': 'Please enter a valid email address',
'val-password2': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long'
},
'val-confirm-password2': {
required: 'Please provide a password',
minlength: 'Your password must be at least 5 characters long',
equalTo: 'Please enter the same password as above'
},
'val-select22': 'Please select a value!',
'val-select2-multiple2': 'Please select at least 2 values!',
'val-suggestions2': 'What can we do to become better?',
'val-skill2': 'Please select a skill!',
'val-currency2': 'Please enter a price!',
'val-website2': 'Please enter your website!',
'val-phoneus2': 'Please enter a US phone!',
'val-digits2': 'Please enter only digits!',
'val-number2': 'Please enter a number!',
'val-range2': 'Please enter a number between 1 and 5!',
'val-terms2': 'You must agree to the service terms!'
}
});
};
// Init Bootstrap Forms Validation
initValidationBootstrap();
// Init Material Forms Validation
initValidationMaterial();
// Init Validation on Select2 change
jQuery('[data-js-select2]').on('change', function(){
jQuery(this).valid();
});
}
]);
// Forms Wizard Controller
App.controller('FormsWizardCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Init simple wizard, for more examples you can check out http://vadimg.com/twitter-bootstrap-wizard-example/
var initWizardSimple = function(){
jQuery('.js-wizard-simple').bootstrapWizard({
'tabClass': '',
'firstSelector': '.wizard-first',
'previousSelector': '.wizard-prev',
'nextSelector': '.wizard-next',
'lastSelector': '.wizard-last',
'onTabShow': function(tab, navigation, index) {
var total = navigation.find('li').length;
var current = index + 1;
var percent = (current/total) * 100;
// Get vital wizard elements
var wizard = navigation.parents('.block');
var progress = wizard.find('.wizard-progress > .progress-bar');
var btnPrev = wizard.find('.wizard-prev');
var btnNext = wizard.find('.wizard-next');
var btnFinish = wizard.find('.wizard-finish');
// Update progress bar if there is one
if (progress) {
progress.css({ width: percent + '%' });
}
// If it's the last tab then hide the last button and show the finish instead
if(current >= total) {
btnNext.hide();
btnFinish.show();
} else {
btnNext.show();
btnFinish.hide();
}
}
});
};
// Init wizards with validation, for more examples you can check out http://vadimg.com/twitter-bootstrap-wizard-example/
var initWizardValidation = function(){
// Get forms
var form1 = jQuery('.js-form1');
var form2 = jQuery('.js-form2');
// Prevent forms from submitting on enter key press
form1.add(form2).on('keyup keypress', function (e) {
var code = e.keyCode || e.which;
if (code === 13) {
e.preventDefault();
return false;
}
});
// Init form validation on classic wizard form
var validator1 = form1.validate({
errorClass: 'help-block animated fadeInDown',
errorElement: 'div',
errorPlacement: function(error, e) {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: function(e) {
jQuery(e).closest('.form-group').removeClass('has-error').addClass('has-error');
jQuery(e).closest('.help-block').remove();
},
success: function(e) {
jQuery(e).closest('.form-group').removeClass('has-error');
jQuery(e).closest('.help-block').remove();
},
rules: {
'validation-classic-firstname': {
required: true,
minlength: 2
},
'validation-classic-lastname': {
required: true,
minlength: 2
},
'validation-classic-email': {
required: true,
email: true
},
'validation-classic-details': {
required: true,
minlength: 5
},
'validation-classic-city': {
required: true
},
'validation-classic-skills': {
required: true
},
'validation-classic-terms': {
required: true
}
},
messages: {
'validation-classic-firstname': {
required: 'Please enter a firstname',
minlength: 'Your firtname must consist of at least 2 characters'
},
'validation-classic-lastname': {
required: 'Please enter a lastname',
minlength: 'Your lastname must consist of at least 2 characters'
},
'validation-classic-email': 'Please enter a valid email address',
'validation-classic-details': 'Let us know a few thing about yourself',
'validation-classic-skills': 'Please select a skill!',
'validation-classic-terms': 'You must agree to the service terms!'
}
});
// Init form validation on the other wizard form
var validator2 = form2.validate({
errorClass: 'help-block text-right animated fadeInDown',
errorElement: 'div',
errorPlacement: function(error, e) {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: function(e) {
jQuery(e).closest('.form-group').removeClass('has-error').addClass('has-error');
jQuery(e).closest('.help-block').remove();
},
success: function(e) {
jQuery(e).closest('.form-group').removeClass('has-error');
jQuery(e).closest('.help-block').remove();
},
rules: {
'validation-firstname': {
required: true,
minlength: 2
},
'validation-lastname': {
required: true,
minlength: 2
},
'validation-email': {
required: true,
email: true
},
'validation-details': {
required: true,
minlength: 5
},
'validation-city': {
required: true
},
'validation-skills': {
required: true
},
'validation-terms': {
required: true
}
},
messages: {
'validation-firstname': {
required: 'Please enter a firstname',
minlength: 'Your firtname must consist of at least 2 characters'
},
'validation-lastname': {
required: 'Please enter a lastname',
minlength: 'Your lastname must consist of at least 2 characters'
},
'validation-email': 'Please enter a valid email address',
'validation-details': 'Let us know a few thing about yourself',
'validation-skills': 'Please select a skill!',
'validation-terms': 'You must agree to the service terms!'
}
});
// Init classic wizard with validation
jQuery('.js-wizard-classic-validation').bootstrapWizard({
'tabClass': '',
'previousSelector': '.wizard-prev',
'nextSelector': '.wizard-next',
'onTabShow': function(tab, nav, index) {
var total = nav.find('li').length;
var current = index + 1;
// Get vital wizard elements
var wizard = nav.parents('.block');
var btnNext = wizard.find('.wizard-next');
var btnFinish = wizard.find('.wizard-finish');
// If it's the last tab then hide the last button and show the finish instead
if(current >= total) {
btnNext.hide();
btnFinish.show();
} else {
btnNext.show();
btnFinish.hide();
}
},
'onNext': function(tab, navigation, index) {
var valid = form1.valid();
if(!valid) {
validator1.focusInvalid();
return false;
}
},
onTabClick: function(tab, navigation, index) {
return false;
}
});
// Init wizard with validation
jQuery('.js-wizard-validation').bootstrapWizard({
'tabClass': '',
'previousSelector': '.wizard-prev',
'nextSelector': '.wizard-next',
'onTabShow': function(tab, nav, index) {
var total = nav.find('li').length;
var current = index + 1;
// Get vital wizard elements
var wizard = nav.parents('.block');
var btnNext = wizard.find('.wizard-next');
var btnFinish = wizard.find('.wizard-finish');
// If it's the last tab then hide the last button and show the finish instead
if(current >= total) {
btnNext.hide();
btnFinish.show();
} else {
btnNext.show();
btnFinish.hide();
}
},
'onNext': function(tab, navigation, index) {
var valid = form2.valid();
if(!valid) {
validator2.focusInvalid();
return false;
}
},
onTabClick: function(tab, navigation, index) {
return false;
}
});
};
// Init simple wizard
initWizardSimple();
// Init wizards with validation
initWizardValidation();
}
]);
// Components Charts Controller
App.controller('CompChartsCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Chart.js Charts, for more examples you can check out http://www.chartjs.org/docs
var initChartsChartJS = function () {
// Get Chart Containers
var chartLinesCon = jQuery('.js-chartjs-lines')[0].getContext('2d');
var chartBarsCon = jQuery('.js-chartjs-bars')[0].getContext('2d');
var chartRadarCon = jQuery('.js-chartjs-radar')[0].getContext('2d');
// Set Chart and Chart Data variables
var chartLines, chartBars, chartRadar;
var chartLinesBarsRadarData;
// Set global chart options
var globalOptions = {
scaleFontFamily: "'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif",
scaleFontColor: '#999',
scaleFontStyle: '600',
tooltipTitleFontFamily: "'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif",
tooltipCornerRadius: 3,
maintainAspectRatio: false,
responsive: true
};
// Lines/Bar/Radar Chart Data
var chartLinesBarsRadarData = {
labels: ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
datasets: [
{
label: 'Last Week',
fillColor: 'rgba(220,220,220,.3)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: [30, 32, 40, 45, 43, 38, 55]
},
{
label: 'This Week',
fillColor: 'rgba(171, 227, 125, .3)',
strokeColor: 'rgba(171, 227, 125, 1)',
pointColor: 'rgba(171, 227, 125, 1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(171, 227, 125, 1)',
data: [15, 16, 20, 25, 23, 25, 32]
}
]
};
// Init Charts
chartLines = new Chart(chartLinesCon).Line(chartLinesBarsRadarData, globalOptions);
chartBars = new Chart(chartBarsCon).Bar(chartLinesBarsRadarData, globalOptions);
chartRadar = new Chart(chartRadarCon).Radar(chartLinesBarsRadarData, globalOptions);
};
// jQuery Sparkline Charts, for more examples you can check out http://omnipotent.net/jquery.sparkline/#s-docs
var initChartsSparkline = function(){
// Bar Charts
var barOptions = {
type: 'bar',
barWidth: 8,
barSpacing: 6,
height: '70px',
barColor: '#fadb7d',
tooltipPrefix: '',
tooltipSuffix: ' Tickets',
tooltipFormat: '{{prefix}}{{value}}{{suffix}}'
};
jQuery('.js-slc-bar1').sparkline('html', barOptions);
barOptions['barColor'] = '#abe37d';
barOptions['tooltipPrefix'] = '$ ';
barOptions['tooltipSuffix'] = '';
jQuery('.js-slc-bar2').sparkline('html', barOptions);
barOptions['barColor'] = '#faad7d';
barOptions['tooltipPrefix'] = '';
barOptions['tooltipSuffix'] = ' Sales';
jQuery('.js-slc-bar3').sparkline('html', barOptions);
// Line Charts
var lineOptions = {
type: 'line',
width: '120px',
height: '70px',
tooltipOffsetX: -25,
tooltipOffsetY: 20,
lineColor: '#fadb7d',
fillColor: '#fadb7d',
spotColor: '#777777',
minSpotColor: '#777777',
maxSpotColor: '#777777',
highlightSpotColor: '#777777',
highlightLineColor: '#777777',
spotRadius: 2,
tooltipPrefix: '',
tooltipSuffix: ' Tickets',
tooltipFormat: '{{prefix}}{{y}}{{suffix}}'
};
jQuery('.js-slc-line1').sparkline('html', lineOptions);
lineOptions['lineColor'] = '#abe37d';
lineOptions['fillColor'] = '#abe37d';
lineOptions['tooltipPrefix'] = '$ ';
lineOptions['tooltipSuffix'] = '';
jQuery('.js-slc-line2').sparkline('html', lineOptions);
lineOptions['lineColor'] = '#faad7d';
lineOptions['fillColor'] = '#faad7d';
lineOptions['tooltipPrefix'] = '';
lineOptions['tooltipSuffix'] = ' Sales';
jQuery('.js-slc-line3').sparkline('html', lineOptions);
// Pie Charts
var pieCharts = {
type: 'pie',
width: '50px',
height: '50px',
sliceColors: ['#fadb7d','#faad7d', '#75b0eb','#abe37d'],
tooltipPrefix: '',
tooltipSuffix: ' Tickets',
tooltipFormat: '{{prefix}}{{value}}{{suffix}}'
};
jQuery('.js-slc-pie1').sparkline('html', pieCharts);
pieCharts['tooltipPrefix'] = '$ ';
pieCharts['tooltipSuffix'] = '';
jQuery('.js-slc-pie2').sparkline('html', pieCharts);
pieCharts['tooltipPrefix'] = '';
pieCharts['tooltipSuffix'] = ' Sales';
jQuery('.js-slc-pie3').sparkline('html', pieCharts);
// Tristate Charts
var tristateOptions = {
type: 'tristate',
barWidth: 8,
barSpacing: 6,
height: '80px',
posBarColor: '#abe37d',
negBarColor: '#faad7d'
};
jQuery('.js-slc-tristate1').sparkline('html', tristateOptions);
jQuery('.js-slc-tristate2').sparkline('html', tristateOptions);
jQuery('.js-slc-tristate3').sparkline('html', tristateOptions);
};
// Randomize Easy Pie Chart values
var initRandomEasyPieChart = function(){
jQuery('.js-pie-randomize').on('click', function(){
jQuery(this)
.parents('.block')
.find('.pie-chart')
.each(function() {
var random = Math.floor((Math.random() * 100) + 1);
jQuery(this)
.data('easyPieChart')
.update(random);
});
});
};
// Flot charts, for more examples you can check out http://www.flotcharts.org/flot/examples/
var initChartsFlot = function(){
// Get the elements where we will attach the charts
var flotLines = jQuery('.js-flot-lines');
var flotStacked = jQuery('.js-flot-stacked');
var flotLive = jQuery('.js-flot-live');
var flotPie = jQuery('.js-flot-pie');
var flotBars = jQuery('.js-flot-bars');
// Demo Data
var dataEarnings = [[1, 2500], [2, 2300], [3, 3200], [4, 2500], [5, 4500], [6, 2800], [7, 3900], [8, 3100], [9, 4600], [10, 3200], [11, 4200], [12, 5700]];
var dataSales = [[1, 1100], [2, 700], [3, 1300], [4, 900], [5, 1900], [6, 950], [7, 1700], [8, 1250], [9, 1800], [10, 1300], [11, 1750], [12, 2900]];
var dataSalesBefore = [[1, 500], [4, 390], [7, 1000], [10, 600], [13, 800], [16, 1050], [19, 1200], [22, 750], [25, 980], [28, 900], [31, 1350], [34, 1200]];
var dataSalesAfter = [[2, 650], [5, 600], [8, 1400], [11, 900], [14, 1300], [17, 1200], [20, 1420], [23, 1650], [26, 1300], [29, 1120], [32, 1550], [35, 1650]];
var dataMonths = [[1, 'Jan'], [2, 'Feb'], [3, 'Mar'], [4, 'Apr'], [5, 'May'], [6, 'Jun'], [7, 'Jul'], [8, 'Aug'], [9, 'Sep'], [10, 'Oct'], [11, 'Nov'], [12, 'Dec']];
var dataMonthsBars = [[2, 'Jan'], [5, 'Feb'], [8, 'Mar'], [11, 'Apr'], [14, 'May'], [17, 'Jun'], [20, 'Jul'], [23, 'Aug'], [26, 'Sep'], [29, 'Oct'], [32, 'Nov'], [35, 'Dec']];
// Init lines chart
jQuery.plot(flotLines,
[
{
label: 'Earnings',
data: dataEarnings,
lines: {
show: true,
fill: true,
fillColor: {
colors: [{opacity: .7}, {opacity: .7}]
}
},
points: {
show: true,
radius: 6
}
},
{
label: 'Sales',
data: dataSales,
lines: {
show: true,
fill: true,
fillColor: {
colors: [{opacity: .5}, {opacity: .5}]
}
},
points: {
show: true,
radius: 6
}
}
],
{
colors: ['#abe37d', '#333333'],
legend: {
show: true,
position: 'nw',
backgroundOpacity: 0
},
grid: {
borderWidth: 0,
hoverable: true,
clickable: true
},
yaxis: {
tickColor: '#ffffff',
ticks: 3
},
xaxis: {
ticks: dataMonths,
tickColor: '#f5f5f5'
}
}
);
// Creating and attaching a tooltip to the classic chart
var previousPoint = null, ttlabel = null;
flotLines.bind('plothover', function(event, pos, item) {
if (item) {
if (previousPoint !== item.dataIndex) {
previousPoint = item.dataIndex;
jQuery('.js-flot-tooltip').remove();
var x = item.datapoint[0], y = item.datapoint[1];
if (item.seriesIndex === 0) {
ttlabel = '$ ' + y + '';
} else if (item.seriesIndex === 1) {
ttlabel = '' + y + ' sales';
} else {
ttlabel = '' + y + ' tickets';
}
jQuery('' + ttlabel + '
')
.css({top: item.pageY - 45, left: item.pageX + 5}).appendTo("body").show();
}
}
else {
jQuery('.js-flot-tooltip').remove();
previousPoint = null;
}
});
// Stacked Chart
jQuery.plot(flotStacked,
[
{
label: 'Sales',
data: dataSales
},
{
label: 'Earnings',
data: dataEarnings
}
],
{
colors: ['#faad7d', '#fadb7d'],
series: {
stack: true,
lines: {
show: true,
fill: true
}
},
lines: {show: true,
lineWidth: 0,
fill: true,
fillColor: {
colors: [{opacity: 1}, {opacity: 1}]
}
},
legend: {
show: true,
position: 'nw',
sorted: true,
backgroundOpacity: 0
},
grid: {
borderWidth: 0
},
yaxis: {
tickColor: '#ffffff',
ticks: 3
},
xaxis: {
ticks: dataMonths,
tickColor: '#f5f5f5'
}
}
);
// Live Chart
var dataLive = [];
function getRandomData() { // Random data generator
if (dataLive.length > 0)
dataLive = dataLive.slice(1);
while (dataLive.length < 300) {
var prev = dataLive.length > 0 ? dataLive[dataLive.length - 1] : 50;
var y = prev + Math.random() * 10 - 5;
if (y < 0)
y = 0;
if (y > 100)
y = 100;
dataLive.push(y);
}
var res = [];
for (var i = 0; i < dataLive.length; ++i)
res.push([i, dataLive[i]]);
// Show live chart info
jQuery('.js-flot-live-info').html(y.toFixed(0) + '%');
return res;
}
function updateChartLive() { // Update live chart
chartLive.setData([getRandomData()]);
chartLive.draw();
setTimeout(updateChartLive, 70);
}
var chartLive = jQuery.plot(flotLive, // Init live chart
[{ data: getRandomData() }],
{
series: {
shadowSize: 0
},
lines: {
show: true,
lineWidth: 2,
fill: true,
fillColor: {
colors: [{opacity: .2}, {opacity: .2}]
}
},
colors: ['#75b0eb'],
grid: {
borderWidth: 0,
color: '#aaaaaa'
},
yaxis: {
show: true,
min: 0,
max: 110
},
xaxis: {
show: false
}
}
);
updateChartLive(); // Start getting new data
// Bars Chart
jQuery.plot(flotBars,
[
{
label: 'Sales Before',
data: dataSalesBefore,
bars: {
show: true,
lineWidth: 0,
fillColor: {
colors: [{opacity: 1}, {opacity: 1}]
}
}
},
{
label: 'Sales After',
data: dataSalesAfter,
bars: {
show: true,
lineWidth: 0,
fillColor: {
colors: [{opacity: 1}, {opacity: 1}]
}
}
}
],
{
colors: ['#faad7d', '#fadb7d'],
legend: {
show: true,
position: 'nw',
backgroundOpacity: 0
},
grid: {
borderWidth: 0
},
yaxis: {
ticks: 3,
tickColor: '#f5f5f5'
},
xaxis: {
ticks: dataMonthsBars,
tickColor: '#f5f5f5'
}
}
);
// Pie Chart
jQuery.plot(flotPie,
[
{
label: 'Sales',
data: 22
},
{
label: 'Tickets',
data: 22
},
{
label: 'Earnings',
data: 56
}
],
{
colors: ['#fadb7d', '#75b0eb', '#abe37d'],
legend: {show: false},
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 2/3,
formatter: function(label, pieSeries) {
return '' + label + '
' + Math.round(pieSeries.percent) + '%
';
},
background: {
opacity: .75,
color: '#000000'
}
}
}
}
}
);
};
// Init all charts
initChartsChartJS();
initChartsSparkline();
initChartsFlot();
// Randomize Easy Pie values functionality
initRandomEasyPieChart();
}
]);
// Components Calendar Controller
App.controller('CompCalendarCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Add new event in the event list
var addEvent = function() {
var eventInput = jQuery('.js-add-event');
var eventInputVal = '';
// When the add event form is submitted
jQuery('.js-form-add-event').on('submit', function(){
eventInputVal = eventInput.prop('value'); // Get input value
// Check if the user entered something
if ( eventInputVal ) {
// Add it to the events list
jQuery('.js-events')
.prepend('' +
jQuery('').text(eventInputVal).html() +
'');
// Clear input field
eventInput.prop('value', '');
// Re-Init Events
initEvents();
}
return false;
});
};
// Init drag and drop event functionality
var initEvents = function() {
jQuery('.js-events')
.find('li')
.each(function() {
var event = jQuery(this);
// create an Event Object
var eventObject = {
title: jQuery.trim(event.text()),
color: event.css('background-color') };
// store the Event Object in the DOM element so we can get to it later
jQuery(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
jQuery(this).draggable({
zIndex: 999,
revert: true,
revertDuration: 0
});
});
};
// Init FullCalendar
var initCalendar = function(){
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
jQuery('.js-calendar').fullCalendar({
firstDay: 1,
editable: true,
droppable: true,
header: {
left: 'title',
right: 'prev,next month,agendaWeek,agendaDay'
},
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = jQuery(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = jQuery.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
jQuery('.js-calendar').fullCalendar('renderEvent', copiedEventObject, true);
// remove the element from the "Draggable Events" list
jQuery(this).remove();
},
events: [
{
title: 'Free day',
start: new Date(y, m, 1),
allDay: true,
color: '#faeab9'
},
{
title: 'Skype Meeting',
start: new Date(y, m, 2)
},
{
title: 'Secret Project',
start: new Date(y, m, 5),
end: new Date(y, m, 8),
allDay: true,
color: '#fac5a5'
},
{
title: 'Work',
start: new Date(y, m, 9),
end: new Date(y, m, 11),
allDay: true,
color: '#fac5a5'
},
{
id: 999,
title: 'Biking (repeated)',
start: new Date(y, m, d - 3, 15, 0)
},
{
id: 999,
title: 'Biking (repeated)',
start: new Date(y, m, d + 2, 15, 0)
},
{
title: 'Landing Template',
start: new Date(y, m, d - 1),
end: new Date(y, m, d - 1),
allDay: true,
color: '#faeab9'
},
{
title: 'Lunch Meeting',
start: new Date(y, m, d + 5, 14, 00),
color: '#fac5a5'
},
{
title: 'Admin Template',
start: new Date(y, m, d, 9, 0),
end: new Date(y, m, d, 12, 0),
allDay: true,
color: '#faeab9'
},
{
title: 'Party',
start: new Date(y, m, 15),
end: new Date(y, m, 16),
allDay: true,
color: '#faeab9'
},
{
title: 'Reading',
start: new Date(y, m, d + 8, 21, 0),
end: new Date(y, m, d + 8, 23, 30),
allDay: true
},
{
title: 'Follow me on Twitter',
start: new Date(y, m, 23),
end: new Date(y, m, 25),
allDay: true,
url: 'http://twitter.com/pixelcave',
color: '#32ccfe'
}
]
});
};
// Add Event functionality
addEvent();
// FullCalendar, for more examples you can check out http://fullcalendar.io/
initEvents();
initCalendar();
}
]);
// Components Syntax Highlighting Controller
App.controller('CompSyntaxHighlightingCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Init HighlightJS
hljs.initHighlighting();
}
]);
// Components Rating Controller
App.controller('CompRatingCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// jQuery Raty, for more examples you can check out https://github.com/wbotelhos/raty
// Init Rating
var initRating = function(){
// Set Default options
jQuery.fn.raty.defaults.starType = 'i';
jQuery.fn.raty.defaults.hints = ['Bad', 'Poor', 'Regular', 'Good', 'Gorgeous'];
// Init Raty on .js-rating class
jQuery('.js-rating').each(function(){
var ratingEl = jQuery(this);
ratingEl.raty({
score: ratingEl.data('score') ? ratingEl.data('score') : 0,
number: ratingEl.data('number') ? ratingEl.data('number') : 5,
cancel: ratingEl.data('cancel') ? ratingEl.data('cancel') : false,
target: ratingEl.data('target') ? ratingEl.data('target') : false,
targetScore: ratingEl.data('target-score') ? ratingEl.data('target-score') : false,
precision: ratingEl.data('precision') ? ratingEl.data('precision') : false,
cancelOff: ratingEl.data('cancel-off') ? ratingEl.data('cancel-off') : 'fa fa-fw fa-times text-danger',
cancelOn: ratingEl.data('cancel-on') ? ratingEl.data('cancel-on') : 'fa fa-fw fa-times',
starHalf: ratingEl.data('star-half') ? ratingEl.data('star-half') : 'fa fa-fw fa-star-half-o text-warning',
starOff: ratingEl.data('star-off') ? ratingEl.data('star-off') : 'fa fa-fw fa-star text-gray',
starOn: ratingEl.data('star-on') ? ratingEl.data('star-on') : 'fa fa-fw fa-star text-warning',
click: function(score, evt) {
// Here you could add your logic on rating click
// console.log('ID: ' + this.id + "\nscore: " + score + "\nevent: " + evt);
}
});
});
};
// Init all Ratings
initRating();
}
]);
// Components Treeview Controller
App.controller('CompTreeviewCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Bootstrap Tree View, for more examples you can check out https://github.com/jonmiles/bootstrap-treeview
// Init Tree Views
var initTreeViews = function(){
// Set default example tree data for all Tree Views
var treeData = [
{
text: 'Bootstrap',
href: '#parent1',
tags: ['4'],
nodes: [
{
text: 'eLearning',
href: '#child1',
tags: ['2'],
nodes: [
{
text: 'Code',
href: '#grandchild1'
},
{
text: 'Tutorials',
href: '#grandchild2'
}
]
},
{
text: 'Templates',
href: '#child2'
},
{
text: 'CSS',
href: '#child3',
tags: ['2'],
nodes: [
{
text: 'Less',
href: '#grandchild3'
},
{
text: 'SaSS',
href: '#grandchild4'
}
]
}
]
},
{
text: 'Design',
href: '#parent3'
},
{
text: 'Coding',
href: '#parent4'
},
{
text: 'Marketing',
href: '#parent5'
}
];
// Init Simple Tree
jQuery('.js-tree-simple').treeview({
data: treeData,
color: '#555',
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showBorder: false,
levels: 3
});
// Init Icons Tree
jQuery('.js-tree-icons').treeview({
data: treeData,
color: '#555',
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
nodeIcon: 'fa fa-folder text-primary',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showBorder: false,
levels: 3
});
// Init Alternative Icons Tree
jQuery('.js-tree-icons-alt').treeview({
data: treeData,
color: '#555',
expandIcon: 'fa fa-angle-down',
collapseIcon: 'fa fa-angle-up',
nodeIcon: 'fa fa-file-o text-city',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showBorder: false,
levels: 3
});
// Init Badges Tree
jQuery('.js-tree-badges').treeview({
data: treeData,
color: '#555',
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
nodeIcon: 'fa fa-folder text-primary',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showTags: true,
levels: 3
});
// Init Collapsed Tree
jQuery('.js-tree-collapsed').treeview({
data: treeData,
color: '#555',
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
nodeIcon: 'fa fa-folder text-primary-light',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showTags: true,
levels: 1
});
// Set example JSON data for JSON Tree View
var treeDataJson = '[' +
'{' +
'"text": "Bootstrap",' +
'"nodes": [' +
'{' +
'"text": "eLearning",' +
'"nodes": [' +
'{' +
'"text": "Code"' +
'},' +
'{' +
'"text": "Tutorials"' +
'}' +
']' +
'},' +
'{' +
'"text": "Templates"' +
'},' +
'{' +
'"text": "CSS",' +
'"nodes": [' +
'{' +
'"text": "Less"' +
'},' +
'{' +
'"text": "SaSS"' +
'}' +
']' +
'}' +
']' +
'},' +
'{' +
'"text": "Design"' +
'},' +
'{' +
'"text": "Coding"' +
'},' +
'{' +
'"text": "Marketing"' +
'}' +
']';
// Init Json Tree
jQuery('.js-tree-json').treeview({
data: treeDataJson,
color: '#555',
expandIcon: 'fa fa-arrow-down',
collapseIcon: 'fa fa-arrow-up',
nodeIcon: 'fa fa-file-code-o text-flat',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showTags: true,
levels: 3
});
};
// Init all Tree Views
initTreeViews();
}
]);
// Components Maps Google Controller
App.controller('CompMapsGoogleCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Gmaps.js, for more examples you can check out https://hpneo.github.io/gmaps/
// Init Search Map
var initMapSearch = function(){
// Init Map
var mapSearch = new GMaps({
div: '#js-map-search',
lat: 20,
lng: 0,
zoom: 2,
scrollwheel: false
});
// When the search form is submitted
jQuery('.js-form-search').on('submit', function(){
GMaps.geocode({
address: jQuery('.js-search-address').val().trim(),
callback: function (results, status) {
if ((status === 'OK') && results) {
var latlng = results[0].geometry.location;
mapSearch.removeMarkers();
mapSearch.addMarker({ lat: latlng.lat(), lng: latlng.lng() });
mapSearch.fitBounds(results[0].geometry.viewport);
} else {
alert('Address not found!');
}
}
});
return false;
});
};
// Init Satellite Map
var initMapSat = function(){
new GMaps({
div: '#js-map-sat',
lat: 0,
lng: 0,
zoom: 1,
scrollwheel: false
}).setMapTypeId(google.maps.MapTypeId.SATELLITE);
};
// Init Terrain Map
var initMapTer = function(){
new GMaps({
div: '#js-map-ter',
lat: 0,
lng: 0,
zoom: 1,
scrollwheel: false
}).setMapTypeId(google.maps.MapTypeId.TERRAIN);
};
// Init Overlay Map
var initMapOverlay = function(){
new GMaps({
div: '#js-map-overlay',
lat: 37.7577,
lng: -122.4376,
zoom: 11,
scrollwheel: false
}).drawOverlay({
lat: 37.7577,
lng: -122.4376,
content: 'Overlay Message
You can overlay messages on your maps!
'
});
};
// Init Markers Map
var initMapMarkers = function(){
new GMaps({
div: '#js-map-markers',
lat: 37.7577,
lng: -122.4376,
zoom: 11,
scrollwheel: false
}).addMarkers([
{lat: 37.70, lng: -122.49, title: 'Marker #1', animation: google.maps.Animation.DROP, infoWindow: {content: 'Marker #1'}},
{lat: 37.76, lng: -122.46, title: 'Marker #2', animation: google.maps.Animation.DROP, infoWindow: {content: 'Marker #2'}},
{lat: 37.72, lng: -122.41, title: 'Marker #3', animation: google.maps.Animation.DROP, infoWindow: {content: 'Marker #3'}},
{lat: 37.78, lng: -122.39, title: 'Marker #4', animation: google.maps.Animation.DROP, infoWindow: {content: 'Marker #4'}},
{lat: 37.74, lng: -122.46, title: 'Marker #5', animation: google.maps.Animation.DROP, infoWindow: {content: 'Marker #5'}}
]);
};
// Init Street Map
var initMapStreet = function(){
new GMaps.createPanorama({
el: '#js-map-street',
lat: 37.809345,
lng: -122.475825,
pov: {heading: 340.91, pitch: 4},
scrollwheel: false
});
};
// Init Geolocation Map
var initMapGeo = function(){
var gmapGeolocation = new GMaps({
div: '#js-map-geo',
lat: 0,
lng: 0,
scrollwheel: false
});
GMaps.geolocate({
success: function(position) {
gmapGeolocation.setCenter(position.coords.latitude, position.coords.longitude);
gmapGeolocation.addMarker({
lat: position.coords.latitude,
lng: position.coords.longitude,
animation: google.maps.Animation.DROP,
title: 'GeoLocation',
infoWindow: {
content: ' Your location!
'
}
});
},
error: function(error) {
alert('Geolocation failed: ' + error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
},
always: function() {
// Message when geolocation succeed
}
});
};
// Init Map with Search functionality
initMapSearch();
// Init Example Maps
initMapSat();
initMapTer();
initMapOverlay();
initMapMarkers();
initMapStreet();
initMapGeo();
}
]);
// Components Maps Google Full Controller
App.controller('CompMapsGoogleFullCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// Gmaps.js, for more examples you can check out https://hpneo.github.io/gmaps/
// Init Full Map
var initMapFull = function(){
var mainCon = jQuery('#main-container');
var mlat = 37.7577;
var mlong = -122.4376;
var rTimeout;
// Set #main-container position to be relative
mainCon.css('position', 'relative');
// Adjust map container position
jQuery('#js-map-full').css({
'position': 'absolute',
'top': mainCon.css('padding-top'),
'right': '0',
'bottom': '0',
'left': '0',
'height': '100%'
});
// Init map itself
var mapFull = new GMaps({
div: '#js-map-full',
lat: mlat,
lng: mlong,
zoom: 11
});
// Set map type
mapFull.setMapTypeId(google.maps.MapTypeId.TERRAIN);
// Resize and center the map on browser window resize
jQuery(window).on('resize orientationchange', function(){
clearTimeout(rTimeout);
rTimeout = setTimeout(function(){
mapFull.refresh();
mapFull.setCenter(mlat, mlong);
}, 150);
});
// Trigger a resize to refresh the map (helps for proper rendering because we dynamically change the height of map's container)
jQuery(window).resize();
};
// Init Full Map
initMapFull();
}
]);
// Components Maps Vector Controller
App.controller('CompMapsVectorCtrl', ['$scope', '$localStorage', '$window',
function ($scope, $localStorage, $window) {
// jVectorMap, for more examples you can check out http://jvectormap.com/documentation/
// Set default options for all maps
var mapOptions = {
container: '',
map: '',
backgroundColor: '#ffffff',
regionStyle: {
initial: {
fill: '#5490d2',
'fill-opacity': 1,
stroke: 'none',
'stroke-width': 0,
'stroke-opacity': 1
},
hover: {
'fill-opacity': .8,
cursor: 'pointer'
}
}
};
// Maps variables
var mapWorld, mapEurope, mapUsa, mapIndia, mapChina, mapAustralia, mapSouthAfrica, mapFrance, mapGermany;
// Init World Map
var initMapWorld = function(){
// Set Active Map and Container
mapOptions['map'] = 'world_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-world');
// Init Map
mapWorld = new jvm.Map(mapOptions);
};
// Init Europe Map
var initMapEurope = function(){
// Set Active Map and Container
mapOptions['map'] = 'europe_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-europe');
// Init Map
mapEurope = new jvm.Map(mapOptions);
};
// Init USA Map
var initMapUsa = function(){
// Set Active Map and Container
mapOptions['map'] = 'us_aea_en';
mapOptions['container'] = jQuery('.js-vector-map-usa');
// Init Map
mapUsa = new jvm.Map(mapOptions);
};
// Init India Map
var initMapIndia = function(){
// Set Active Map and Container
mapOptions['map'] = 'in_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-india');
// Init Map
mapIndia = new jvm.Map(mapOptions);
};
// Init China Map
var initMapChina = function(){
// Set Active Map and Container
mapOptions['map'] = 'cn_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-china');
// Init Map
mapChina = new jvm.Map(mapOptions);
};
// Init Australia Map
var initMapAustralia = function(){
// Set Active Map and Container
mapOptions['map'] = 'au_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-australia');
// Init Map
mapAustralia = new jvm.Map(mapOptions);
};
// Init South Africa Map
var initMapSouthAfrica = function(){
// Set Active Map and Container
mapOptions['map'] = 'za_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-south-africa');
// Init Map
mapSouthAfrica = new jvm.Map(mapOptions);
};
// Init France Map
var initMapFrance = function(){
// Set Active Map and Container
mapOptions['map'] = 'fr_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-france');
// Init Map
mapFrance = new jvm.Map(mapOptions);
};
// Init Germany Map
var initMapGermany = function(){
// Set Active Map and Container
mapOptions['map'] = 'de_mill_en';
mapOptions['container'] = jQuery('.js-vector-map-germany');
// Init Map
mapGermany = new jvm.Map(mapOptions);
};
// Init Example Maps
initMapWorld();
initMapEurope();
initMapUsa();
initMapIndia();
initMapChina();
initMapAustralia();
initMapSouthAfrica();
initMapFrance();
initMapGermany();
// When leaving the page remove maps resize event (causes JS errors in other pages)
$scope.$on('$stateChangeStart', function(event) {
jQuery(window).unbind('resize', mapWorld.onResize);
jQuery(window).unbind('resize', mapEurope.onResize);
jQuery(window).unbind('resize', mapUsa.onResize);
jQuery(window).unbind('resize', mapIndia.onResize);
jQuery(window).unbind('resize', mapChina.onResize);
jQuery(window).unbind('resize', mapAustralia.onResize);
jQuery(window).unbind('resize', mapSouthAfrica.onResize);
jQuery(window).unbind('resize', mapFrance.onResize);
jQuery(window).unbind('resize', mapGermany.onResize);
});
// When returning to the page re-enable maps resize functionality
$scope.$on('$stateChangeSuccess', function(event) {
jQuery(window).resize(mapWorld.onResize);
jQuery(window).resize(mapEurope.onResize);
jQuery(window).resize(mapUsa.onResize);
jQuery(window).resize(mapIndia.onResize);
jQuery(window).resize(mapChina.onResize);
jQuery(window).resize(mapAustralia.onResize);
jQuery(window).resize(mapSouthAfrica.onResize);
jQuery(window).resize(mapFrance.onResize);
jQuery(window).resize(mapGermany.onResize);
});
}
]);App.controller('CharityCategoryCtrl', ['$scope', '$localStorage', '$http', '$stateParams', '$state','$rootScope',
function ($scope, $localStorage, $http, $stateParams, $state,$rootScope) {
$scope.isCharityClaim = false;
if( $state.current.name == 'charity-category-for-claim' )
$scope.isCharityClaim = true;
$scope.category = '';
$http.get('/api/website/charity-categories/').then(function(response) {
$scope.category = response.data[$stateParams.id];
$rootScope.metaservice.set("My Charity Fund - "+ $scope.category,"Browse all "+ $scope.category+" in Canada.", $scope.category+", charity, tax receipt, canadian, find, browse");
$scope.doSearch();
});
$scope.doSearch = function(){
$http.post('/api/website/search',{ page:1, categories: [$scope.category] }).then(function(response) {
$scope.results = response.data.data;
});
}
}
]);
App.controller('CharityUnpaidCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$scope.totalOwing = 0;
$http.get('/api/website/charity/'+$stateParams.charity+'/unpaid').then(function(response) {
$scope.unpaid = response.data.data;
for(i in $scope.unpaid)
$scope.totalOwing += parseFloat($scope.unpaid[i].amount);
setTimeout("jQuery('#myTable').DataTable({dom: 'Bfrtip' , \
buttons: [ \
'copy',{extend: 'csv',title:'Unpaid Donations'}, {extend: 'excel',title:'Unpaid Donations'},\
{extend: 'print',title:'Unpaid Donations'} \
] });",500);
});
}
]);App.controller('CharityClaimFormCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$rootScope.metaservice.set("My Charity Fund - Claim Your Charity","Prove that you manage this charity to be able to control its look and feel, get instant notificaitons on donations and payments and more!","claim, manage, owner, director, charity, tax receipt, canadian, donate","noindex, nofollow");
$http.get('/api/website/charity/'+$stateParams.id).then(function(response) {
$scope.charity = response.data.data;
});
$scope.user = { fname:'',lname:''};
$scope.labelStyle = {};
if($rootScope.me){
$scope.user = $rootScope.me;
$scope.labelStyle = {top:'-30px'};
}
$scope.buttonText = 'Claim Your Charity';
$scope.claimCharity = function(){
if( $scope.buttonText != 'Claim Your Charity')
return;
$scope.buttonText = 'Processing, please wait...';
$http.post('/api/website/claim-charity/'+$stateParams.id,$scope.user).then(function(response) {
if(response.data.success){
/*if(response.data.data.token && !$rootScope.me)
$rootScope.doLogin(response.data.data.token);
else
*/
$state.go('thanks-claim');
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Claim Your Charity';
}
},function(response) {
for(i in response.data){
$.notify(response.data[i],{globalPosition: 'top center'});
$scope.buttonText = 'Claim Your Charity';
break;
}
});
}
window.charity_id = $stateParams.id;
setTimeout(" var dz = jQuery('#dropzone').dropzone({\
url: '/api/website/charity-doc/'+ window.charity_id,\
headers: { 'Authorization': localStorage.token } ,\
createImageThumbnails : false,\
acceptedFiles: 'image/*,application/pdf',\
init: function() {\
this.on('success', function(file) {\
var response = JSON.parse(file.xhr.response);\
$('.uploadField,#dropzone').hide();$('#fileUploaded').show()\
});\
}\
});",1500);
}
]);
App.controller('WithdrawalBatchCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope', '$timeout',
function ($scope, $http, $stateParams, $state, $rootScope,$timeout) {
$scope.account_id = false;
$scope.account = false;
$scope.canSelectFund = false;
$scope.account_withdrawal = {account_id:false,charity_id:'',dedication:'in honour of', privacy_level: 'name email and address'};
$scope.withdrawals = [];
$scope.totalAmount = function(){
var total = 0;
for(i in $scope.withdrawals)
total += parseFloat($scope.withdrawals[i].amount);
return total;
}
$scope.buttonText = 'Make Donation';
$scope.charitySelector = 'search';
$scope.initWithdrawal = function(){
if(!$rootScope.me){
$timeout($scope.initWithdrawal,50);
return;
}
$scope.isFavouriteCharitySelector = $rootScope.me.favourites.length;
if($stateParams.account)
$scope.account_id = $stateParams.account;
else
$scope.account_id =$rootScope.me.accounts[0].id;
if($scope.account_id)
for(i in $rootScope.me.accounts)
if($rootScope.me.accounts[i].id == $scope.account_id){
$scope.account = $rootScope.me.accounts[i]
$scope.account_withdrawal.privacy_level = $rootScope.me.accounts[i].privacy_level;
$scope.account_withdrawal.account_id = $rootScope.me.accounts[i].id;
}
$scope.charitySelector = 'search';
};
$scope.initWithdrawal();
var icon;
setTimeout(function(){
jQuery('input#charity').flexdatalist({
cache:false,
normalizeString: function (string) {
return string.replace("'",''); //ignore ' in searches so "bnai" will return "b'nai" and vice versa
}
});
icon = $('i.icon.icon-Magnifi-Glass2');
$('input#charity').on('before:flexdatalist.data', function() {
icon.addClass('fa-spin');
});
$('input#charity').on('after:flexdatalist.data', function() {
icon.removeClass('fa-spin');
});
},100);
$scope.$watch('account_withdrawal.charity_id', function(newValue, oldValue) {
if(parseInt(newValue) > 0)
$http.get('/api/website/charity/'+$scope.account_withdrawal.charity_id).then(function(response) {
$scope.charity = response.data.data;
$scope.isFavourite = false;
for(i in $rootScope.me.favourites)
if($scope.charity.id == $rootScope.me.favourites[i].id)
$scope.isFavourite = true;
});
});
$scope.makeDonation = function(){
if($scope.totalAmount() > $scope.account.balance){
$.notify('You do not have enough funds in your account to make these donations',{globalPosition: 'top center'});
return;
}
if(!confirm('Are you sure you want to make donations to '+$scope.withdrawals.length+' charities totalling $'+$scope.totalAmount())){
return; //processing donation
}
$rootScope.canExitBatchWithdrawal = true;
$scope.buttonText = 'Please wait...';
$http.post('/api/website/withdrawal/batch',$scope.withdrawals).then(function(response) {
if(response.data.success){
$rootScope.me = response.data.data;
$state.go('thanks-fund');
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Make Donation';
$rootScope.canExitBatchWithdrawal = false;
}
},function(){
$.notify('Error processing donations',{globalPosition: 'top center'});
$scope.buttonText = 'Make Donation';
$rootScope.canExitBatchWithdrawal = false;
});
}
$scope.clearDonations = function(){
$scope.withdrawals = [];
$scope.account_withdrawal = {account_id:false,charity_id:'',dedication:'in honour of', privacy_level: $scope.account.privacy_level};
$scope.charity = false;
}
$scope.addDonation = function(){
if($scope.isFavouriteCharitySelector){
$scope.account_withdrawal.charity_id = $scope.favourite_charity_id;
for(i in $rootScope.me.favourites)
if($scope.favourite_charity_id == $rootScope.me.favourites[i].id)
$scope.charity = $rootScope.me.favourites[i];
}
if(!$scope.charity){
$.notify('Please select a charity',{globalPosition: 'top center'});
return;
}
if(isNaN(parseFloat($scope.account_withdrawal.amount)) || $scope.account_withdrawal.amount < 0.01){
$.notify('Please enter a valid donation amount',{globalPosition: 'top center'});
return;
}
if(parseFloat($scope.account_withdrawal.amount)+$scope.totalAmount() > $scope.account.balance){
$.notify('Insufficient funds available to add this donation',{globalPosition: 'top center'});
return;
}
//$scope.totalAmount += parseFloat($scope.account_withdrawal.amount);
$scope.account_withdrawal.account_id = $scope.account.id;
$scope.account_withdrawal.charity = $scope.charity;
$scope.withdrawals.push($scope.account_withdrawal);
$scope.account_withdrawal = {account_id:false,charity_id:'',dedication:'in honour of', privacy_level: $scope.account.privacy_level};
$scope.charity = false;
$scope.favourite_charity_id=false;
};
$scope.removeDonation = function(w){
for(i in $scope.withdrawals)
if($scope.withdrawals[i] == w)
$scope.withdrawals.splice(i,1);
//$scope.totalAmount -= parseFloat(w.amount);
}
//favourites
$scope.isFavourite = false;
$scope.addFavourite = function(){
if($scope.isFavourite)
return;
$rootScope.me.favourites.push($scope.charity);
$scope.isFavourite = true;
$http.post('/api/website/favourite/add/'+$scope.charity.id);
}
$scope.removeFavourite = function(){
if(!$scope.isFavourite)
return;
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($scope.charity.id == $rootScope.me.favourites[i].id)
$rootScope.me.favourites.splice(i,1);
$scope.isFavourite = false;
$http.post('/api/website/favourite/remove/'+$scope.charity.id);
}
}
]);
App.controller('AuthorizeCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$rootScope.metaservice.set("My Charity Fund - Authorize user","Authorize user to view/edit charity.","");
setTimeout(" if(typeof grecaptcha !== typeof undefined) mr.forms.captcha.renderWidgets ();",100);
$scope.buttonText = 'Submit';
$scope.authorize = {
date: '',
charity_name: '',
charity_number: '',
new_user_name: '',
new_user_position: '',
name: '',
position: ''
};
$scope.formReset = function() {
$scope.authorize = {
date: '',
charity_name: '',
charity_number: '',
new_user_name: '',
new_user_position: '',
name: '',
position: ''
};
$scope.buttonText = 'Submit';
}
$scope.submitForm = function($e){
$e.preventDefault();
if( $scope.buttonText != 'Submit')
return;
$scope.buttonText = 'Processing, please wait...';
$http.post('/api/website/authorize-user', $scope.authorize).then(function(response) {
if(response.data.success == "200"){
$.notify("Done.",{globalPosition: 'top center', className: 'success'});
$scope.formReset();
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Submit';
}
});
}
}
]);
App.controller('CharityHistoryCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope', '$compile',
function ($scope, $http, $stateParams, $state, $rootScope,$compile) {
$scope.donationsPerPayment = {};
$scope.selectPayment = function(p){
$scope.selectedPayment = p;
}
$scope.setThanks = function(id){
today = new Date().toISOString().slice(0,10);
$http.post('/api/website/charity-donation-thank/'+id).then(function(response){
// Success callback - only 2xx status codes
if(response.status == 200)
jQuery('#thanks-'+id).html('Sent '+today);
else
alert("We were unable to mark the thank you as sent. Please try again later.");
}, function(response){
// Error callback - handles 401, 500, etc.
if(response.status == 401)
alert("We were unable to mark the thank you as sent. You may have been logged out due to inactivity");
else
alert("We were unable to mark the thank you as sent. Please try again later.");
});
}
$scope.unsetThanks = function(id){
if(confirm('Are you sure you want to mark this donation as not having received a thank you?')) {
$http.post('/api/website/charity-donation-remove-thank/' + id).then(function(response){
// Success callback - only 2xx status codes
if(response.status == 200)
jQuery('#thanks-'+id).html('Marked as not sent');
else
alert("We were unable to mark the thank you as not sent. Please try again later.");
}, function(response){
// Error callback - handles 401, 500, etc.
if(response.status == 401)
alert("We were unable to mark the thank you as not sent. You may have been logged out due to inactivity");
else
alert("We were unable to mark the thank you as not sent. Please try again later.");
});
}
}
$scope.selectedPayment = '0';
$scope.charity_id = $stateParams.charity;
$scope.campaign = false;
if($stateParams.campaign){
for (var i in $rootScope.me.charities)
if ($rootScope.me.charities[i].id == $stateParams.charity)
for (var j in $rootScope.me.charities[i].campaigns)
if ($rootScope.me.charities[i].campaigns[j].id == $stateParams.campaign) {
$scope.campaign = $rootScope.me.charities[i].campaigns[j];
$http.get('/api/website/campaign/'+$scope.campaign.id).then(function(response) {
$scope.donations_total = response.data.data.donations_total;
$scope.goal = response.data.data.goal;
});
}
}
$scope.donations = [];
$scope.payments = [];
setTimeout(function(){
columns = [
{ "data": "donor", name: 'donor' },
{ "data": "amount" , name:"account_withdrawal.amount",render: function ( data, type, row ) {
if(type == 'display') {
if(data == '' || isNaN(data))
return data;
data = parseFloat(data);
return data.toLocaleString('en-US', {style:'currency', currency:'USD'});
}
return data;
} },
{ "data": "dedication", "name": "dedication"},
{ "data": "memo", "name": "memo"},
{ "data": "donor_email", "name": "donor_email",render: function ( data, type, row ) {
if(type != 'display' || data.indexOf('@') < 1)
return data;
return ''+data+''
}},
{ "data": "donor_address", "name": "donor_address"},
{ "data": "thanks", "name": "thank_you_sent_date",render: function ( data, type, row ) {
if(type != 'display')
return data;
if(!data)
return '';
return '';
}},
{ "data": "charity_payment_id", "name": "charity_payment_id",render: function ( data, type, row ) {
if(type != 'display')
return data;
if(!data)
return 'Unpaid';
return 'P'+data+'';
}},
];
if(!$scope.campaign)
columns.unshift({ "data": "campaign", name:"charity_campaign.title" });
columns.unshift(
{ "data": "created_at", name:"account_withdrawal.created_at",render: function ( data, type, row ) {
if(type == 'display') {
return data.split(' ')[0];
}
return data;
} });
jQuery('#myTableTransactions').DataTable({
lengthMenu: [[10, 20, 50, 100,-1], [10, 20, 50, 100,'All']],
order: [[ 0, 'desc' ]],
dom: 'Blfrtip',
processing: true,
serverSide: true,
ajax: {
url: "/api/website/charity/"+ $scope.charity_id+"/transactions",
type: 'GET',
beforeSend: function (request) {
request.setRequestHeader("Authorization", localStorage.token);
},
data: {
"campaign_id": $scope.campaign.id
}
},
columns: columns,
createdRow: function ( row, data, index ) {
$compile(row)($scope); //add this to compile the DOM
},
buttons: [
'copy',{extend: 'csv',title:'My Charity Fund Report'}, {extend: 'excel',title:'My Charity Fund Report'},
{extend: 'print',title:'My Charity Fund Report'}
] })},500);
}
]);
App.controller('DashboardCtrl', ['$scope', '$rootScope', '$window', '$state', '$timeout',
function ($scope, $rootScope, $window, $state, $timeout) {
$scope.today = new Date().toISOString().split('T')[0];
$scope.fundName = function(id){
id = parseInt(id);
for(i in $rootScope.me.accounts)
if(parseInt($rootScope.me.accounts[i].id) == id)
return $rootScope.me.accounts[i].name;
return "unknown fund";
};
//the growth popup is supposed to show for the whole week from January 16th to January 22nd
//if the date is after that, check if there is a localstorage variable set for growthPopupDisplayed
//if there is, do nothing.
//if there is not, set showGrowthPopup to true and set a localstorage variable for growthPopupDisplayed
$scope.showGrowthPopup = false;
var today = new Date();
var february6 = new Date('2024-02-06');
if(today < february6){
$scope.showGrowthPopup = true;
} else {
if(localStorage.getItem('growthPopupDisplayed') == null){
$scope.showGrowthPopup = true;
localStorage.setItem('growthPopupDisplayed', true);
}
}
$scope.dashboardInit = function() {
$scope.activity = [];
$scope.alertNewGrowthFunds();
//show sidebar, it doesn't show if you log in from the home page after a reload/cache clear
jQuery('.nav-container').css('display','block');
if($rootScope.me.recent && $rootScope.me.recent.deposits)
for (i in $rootScope.me.recent.deposits) {
d = $rootScope.me.recent.deposits[i];
var text = '$' + d.amount;
if (d.payment_method == 'transfer')
text += ' transferred';
else
text += ' deposited';
if ($rootScope.me.accounts.length > 1)
text += ' to the ' + $scope.fundName(d.account_id) + ' Fund';
text += ' on ' + d.created_at.split(' ')[0] + '.';
$scope.activity.push({
timestamp: d.created_at,
url: '/#/deposits/' + d.id,
text: text
});
}
if($rootScope.me.recent && $rootScope.me.recent.withdrawals)
for (i in $rootScope.me.recent.withdrawals) {
w = $rootScope.me.recent.withdrawals[i];
//console.log('withdrawal',w);
var text = '$' + w.amount + ' donated';
if ($rootScope.me.accounts.length > 1)
text += ' from the ' + $scope.fundName(w.account_id) + ' Fund';
text += ' to ' + w.charity + ' on ' + w.created_at.split(' ')[0] + '.';
$scope.activity.push({
timestamp: w.created_at,
url: '/#/withdrawals/' + w.id,
text: text
});
}
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = new Date(a[key].replace(/-/g, '/')); var y = new Date(b[key].replace(/-/g, '/'));
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
$scope.activity = sortByKey($scope.activity,'timestamp');
//console.log('activbity',$scope.activity);
};
$scope.alertNewGrowthFunds = function() {
if(!$rootScope.me.accounts)
setTimeout($scope.alertNewGrowthFunds,1000);
else {
for(account of $rootScope.me.accounts) {
if($rootScope.showInvestmentPopup) {
$rootScope.showInvestmentPopup = false;
$.notify(`Congrats on setting up your Growth Account!
On the left menu, you will find a Cash Account and Growth Account.
To deposit funds into your Growth Account please click on Add Funds in the Growth Account menu.
Your Cash Account enables you to make disbursements to charities. To start making disbursements, please click on Make a Deposit in the Cash Account menu.
`, { className:"success showButton"});
break;
}
}
}
}
$timeout($scope.dashboardInit,1);
var closePopup = $("#close-popup");
closePopup.click(function() {
closePopup.closest(".modal-overlay").css("display", "none");
$scope.showGrowthPopup = false;
});
}
]);App.controller('CharitiesCtrl', ['$scope', '$localStorage', '$http','$state', '$rootScope',
function ($scope, $localStorage, $http, $state, $rootScope) {
$rootScope.metaservice.set("My Charity Fund - Find a Canadian Charity","Search for a Canadian Charity by name, location or category. Find the right charity to donate to today.","charity, tax receipt, canadian, donate");
$http.get('/api/website/charity-categories/').then(function(response) {
$scope.categories = response.data;
});
$scope.isCharityClaim = false;
if( $state.current.name == 'charities-find-for-claim' )
$scope.isCharityClaim = true;
$scope.search = { page:1 };
$scope.doSearch = function(){
$scope.search.page = 1;
$scope.search.categories = [];
jQuery(':checked').each(function(){$scope.search.categories.push(jQuery(this).val() )});
$http.post('/api/website/search',$scope.search).then(function(response) {
$scope.results = response.data.data;
jQuery('html,body').animate({
scrollTop: jQuery("#scrollHere").offset().top - 80
});
});
}
}
]);
App.controller('HomeCtrl', ['$scope', '$rootScope', '$window', '$state',
function ($scope, $rootScope, $window, $state) {
$('.background-image-holder').each(function() {
var imgSrc = $(this).children('img').attr('src');
$(this).css('background', 'url("' + imgSrc + '")').css('background-position', 'initial').css('opacity','1');
});
$('input.search').flexdatalist({
cache:false,
normalizeString: function (string) {
return string.replace("'",''); //ignore ' in searches so "bnai" will return "b'nai" and vice versa
}
});
var icon = $('i.icon.icon-Magnifi-Glass2');
$('input.search').on('before:flexdatalist.data', function() {
icon.addClass('fa-spin');
});
$('input.search').on('after:flexdatalist.data', function() {
icon.removeClass('fa-spin');
});
$scope.charity ='';
$scope.$watch('charity', function(newValue, oldValue) {
if(parseInt(newValue) > 0)
$state.go('charity',{id:newValue, name: $rootScope.slugify($('#flex0').val())});
});
if($state.current.name == 'comparison'){
jQuery('html,body').animate({
scrollTop: jQuery(".pricing-section-2").offset().top -100
});
}
$rootScope.metaservice.set("My Charity Fund","My Charity Fund is an online charitable donation platform. You deposit money, get an instant tax receipt and make donations to any Registered Canadian Charity. At any time you can conveniently access all your tax receipts and view all your account activity.","charity, tax receipt, canadian, donate, fund","index, follow");
}
]);
App.controller('TransferCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$scope.buttonText = 'Transfer Funds';
$scope.from = null;
$scope.to = null;
$scope.fromOptions = $rootScope.me.accounts.map(function(account){
if(account.type != 'investment'){
return {
value: account.id,
label: `${account.name} - #${account.id} ($${account.balance})`
};
};
});
//i don't want to have any undefined values in the fromOptions array
$scope.fromOptions = $scope.fromOptions.filter(function(option){
return option != undefined;
});
$scope.toOptions = $scope.fromOptions;
//now let's make an updateToOptions function which will remove the from account from the toOptions
$scope.updateToOptions = function(from){
$scope.toOptions = $scope.fromOptions.filter(function(option){
return option.value != from;
});
}
$scope.transfer = function(){
$scope.amount = $scope.amount.replace(/[^\d.]/g, '');
if( $scope.buttonText != 'Transfer Funds')
return;
if(!$scope.from){
$.notify('Please select a fund to transfer from',{globalPosition: 'top center'});
return;
}
if(!$scope.to){
$.notify('Please select a fund to transfer to',{globalPosition: 'top center'});
return;
}
if($scope.from == $scope.to){
$.notify('Invalid fund selection. The to and from funds can not be the same',{globalPosition: 'top center'});
return;
}
if($scope.amount === undefined || isNaN(parseFloat($scope.amount)) || parseFloat($scope.amount) < 0.01){
$.notify('Invalid transfer amount',{globalPosition: 'top center'});
return;
}
$scope.buttonText = 'Processing...';
$http.post('/api/website/transfer',{
from: $scope.from,
to: $scope.to,
memo: $scope.memo,
amount: parseFloat($scope.amount)
}).then(function(response) {
if(response.data.success){
$rootScope.me = response.data.data;
$state.go('dashboard');
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Transfer Funds';
}
},function(){
$.notify('Error processing transfer',{globalPosition: 'top center'});
$scope.buttonText = 'Transfer Funds';
});
}
}
]);
App.controller('ContactCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$rootScope.metaservice.set("My Charity Fund - Contact Us","Contact My Charity Fund to provide feedback and ask quetions.","contact, feedback, questions, contact us");
setTimeout(" if(typeof grecaptcha !== typeof undefined) mr.forms.captcha.renderWidgets ();",100);
}
]);
App.controller('CharityPaymentsCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$scope.donationsPerPayment = {};
$scope.selectPayment = function(p){
$scope.selectedPayment = p;
}
$scope.setThanks = function(d){
d.thanks = new Date().toISOString().slice(0,10);
$http.post('/api/website/charity-donation-thank/'+d.id);
}
$scope.unsetThanks = function(d){
if(confirm('Are you sure you want to mark this donation as not having received a thank you?')) {
d.thanks = '';
$http.post('/api/website/charity-donation-remove-thank/' + d.id);
}
}
$http.get('/api/website/charity/'+$stateParams.charity+'/history').then(function(response) {
$scope.donations = response.data.data.donations;
$scope.payments = response.data.data.payments;
for(i in $scope.donations){
d = $scope.donations[i];
if(!$scope.donationsPerPayment[d.payment])
$scope.donationsPerPayment[d.payment] = [];
$scope.donationsPerPayment[d.payment].push(d);
}
$scope.selectedPayment = '0';
$scope.charity_id = $stateParams.charity;
$scope.campaign = false;
if($stateParams.campaign){
for (var i in $rootScope.me.charities)
if ($rootScope.me.charities[i].id == $stateParams.charity)
for (var j in $rootScope.me.charities[i].campaigns)
if ($rootScope.me.charities[i].campaigns[j].id == $stateParams.campaign)
$scope.campaign = $rootScope.me.charities[i].campaigns[j];
}
//column is 2 or 3 depending on if there is a campaign so we check for NaN
setTimeout("jQuery('#myTable').DataTable({lengthMenu: [[10, 20, 50, 100,-1], [10, 20, 50, 100,'All']],'order': [[ 0, 'desc' ]], dom: 'Blfrtip', \
\"columnDefs\": [{ \"render\": function ( data, type, row ) {\
if(type == 'display') {\
if(data == '' || isNaN(data))\
return data;\
data = parseFloat(data);\
return data.toLocaleString('en-US', {style:'currency', currency:'USD'});\
}\
return data;\
},\
\"targets\": [2,3]\
},{ \"render\": function ( data, type, row ) {\
if(type == 'display') {\
return data.split(' ')[0];\
}\
return data;\
},\
\"targets\": 0\
}],\
buttons: [ \
'copy',{extend: 'csv',title:'My Charity Fund Report'}, {extend: 'excel',title:'My Charity Fund Report'},\
{extend: 'print',title:'My Charity Fund Report'} \
] });",500);
});
}
]);
App.controller('DepositViewCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$http.get('/api/website/deposits/'+$stateParams.id).then(function(response) {
$scope.deposit = response.data.data;
});
$scope.download = function(){
$http.get('/api/website/receipt/'+$stateParams.id).then(function(response) {
window.open('/pdfs/'+response.data.data.file+'.pdf','_blank');
});
}
}
]);
App.controller('LoginCtrl', ['$scope', '$rootScope', '$localStorage', '$http', '$state',
function ($scope, $rootScope, $localStorage, $http, $state) {
if($rootScope.me)
$state.go('dashboard');
else
$rootScope.metaservice.set("My Charity Fund - Login","Login to your charity accounts.","login, account, donate");
$scope.login = function(){
$http.post('/api/website/login',{email:$scope.email,password:$scope.password}).then(function(response) {
if(response.data.success)
$rootScope.doLogin(response.data.data.token,true);
else
$.notify(response.data.data,{globalPosition: 'top center'});
},function(response) {
for(i in response.data){
$.notify(response.data[i],{globalPosition: 'top center'});
break;
}
});
}
}
]);App.controller('CharityCampaignsCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope)
{
$scope.title = '';
$scope.goal = '';
$scope.fetchCharity = function ()
{
if(!$rootScope.me.charities)
{
setTimeout($scope.fetchCharity,100);
}
for (var i in $rootScope.me.charities)
{
if ($rootScope.me.charities[i].id == $stateParams.charity)
$scope.charity = $rootScope.me.charities[i];
}
}
$scope.fetchCharity();
$scope.copy = (string, scrollToY) =>
{
let textarea;
let result;
try
{
textarea = document.createElement('textarea');
textarea.setAttribute('readonly', true);
textarea.setAttribute('contenteditable', true);
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.style.top = document.body.scrollTop + window.innerHeight / 2 + 'px';
textarea.value = string;
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, textarea.value.length);
result = document.execCommand('copy');
} catch (err)
{
result = null;
} finally
{
document.body.removeChild(textarea);
}
if (!result)
{
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
const copyHotkey = isMac ? '⌘C' : 'CTRL+C';
result = prompt(`Press ${copyHotkey}`, string);
if (!result)
{
return false;
}
}
return true;
}
$scope.addCampaign = function (id)
{
$http.post('/api/website/add-campaign/' + $scope.charity.id, { title: $scope.title, goal: $scope.goal }).then(function (response)
{
if (response.data.success)
{
$scope.title = '';
$scope.goal = '';
$rootScope.me = response.data.data;
$scope.fetchCharity();
}
else
{
$.notify(response.data.data, { globalPosition: 'top center' });
}
}, function ()
{
$.notify('Error saving changes', { globalPosition: 'top center' });
});
}
$scope.toggleCampaignInMenu = function (campaign)
{
$http.post('/api/website/campaign-menu-toggle/' + campaign.id, { }).then(function (response)
{
if (response.data.success)
{
if(campaign.show_in_menu > 0)
campaign.show_in_menu = 0;
else
campaign.show_in_menu = 1;
}
else
{
$.notify(response.data.data, { globalPosition: 'top center' });
}
}, function ()
{
$.notify('Error saving changes', { globalPosition: 'top center' });
});
};
$scope.onCampaignLinkClick = (e) =>
{
const link = e.target.href;
const tooltip = 'Link has been copied to your clipboard.';
e.preventDefault();
$scope.copy(link, e.target.offsetTop);
$('a[data-tooltip="' + tooltip + '"]').removeAttr('data-tooltip');
let attr = document.createAttribute('data-tooltip');
attr.value = tooltip;
e.target.attributes.setNamedItem(attr);
}
$scope.deleteCampaign = function (id)
{
if (confirm('Are you sure you want to delete this campaign?'))
$http.post('/api/website/delete-campaign/' + id).then(function (response)
{
if (response.data.success)
{
$rootScope.me = response.data.data;
$scope.fetchCharity();
}
else
{
$.notify(response.data.data, { globalPosition: 'top center' });
}
}, function ()
{
$.notify('Error saving changes', { globalPosition: 'top center' });
});
}
/*
$http.get('/api/website/charity/'+$stateParams.charity+'/campaigns').then(function(response) {
$scope.campaigns = response.data.data;
});
*/
}
]);App.controller('CampaignCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope', '$sce','$timeout',
function ($scope, $http, $stateParams, $state, $rootScope, $sce,$timeout) {
$http.get('/api/website/campaign/'+$stateParams.id).then(function(response) {
$scope.charity = response.data.data.charity;
$scope.campaign = response.data.data;
//if($scope.charity.public_name != null)
// $scope.charity.name = $scope.charity.public_name;
if($scope.charity.public_phone != null && $scope.charity.public_phone != '')
$scope.charity.phone_number = $scope.charity.public_phone;
if($scope.charity.analytics_code != null)
gtag('config', $scope.charity.analytics_code);
$rootScope.metaservice.set("My Charity Fund - "+$scope.charity.name,"Donate online to "+$scope.charity.name+".",
$scope.charity.name+","+ $scope.charity.charity_number+","+$scope.charity.designation+", charity, tax receipt, canadian, donate","index, nofollow");
// This is a quick and dirty fix to remove the "Campaign of" wording
// before the charity name for this particular campaign.
$scope.campaign.subtitle = $scope.campaign.title == 'Amek Adler Legacy Fund'
? 'March of the Living Canada Campaign at the Jewish Foundation of Greater Toronto'
: 'Campaign of ' + $scope.charity.name + (!$scope.charity.public_name.length ? '' : ' ('+$scope.charity.public_name+')');
});
$scope.isFavourite = false;
$scope.setIsFavourite = function(){
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($stateParams.id == $rootScope.me.favourites[i].id)
$scope.isFavourite = true;
}
$scope.setIsFavourite();
$timeout(function(){$scope.setIsFavourite();},500);
$timeout(function(){$scope.setIsFavourite();},2000);
$scope.addFavourite = function(){
if($scope.isFavourite)
return;
$rootScope.me.favourites.push($scope.charity);
$scope.isFavourite = true;
$http.post('/api/website/favourite/add/'+$stateParams.id);
}
$scope.removeFavourite = function(){
if(!$scope.isFavourite)
return;
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($stateParams.id == $rootScope.me.favourites[i].id)
$rootScope.me.favourites.splice(i,1);
$scope.isFavourite = false;
$http.post('/api/website/favourite/remove/'+$stateParams.id);
}
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
}
]);
App.controller('CharityCampaignPageCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope','$sce','$timeout','$filter',
function ($scope, $http, $stateParams, $state, $rootScope, $sce,$timeout,$filter) {
for (var i in $rootScope.me.charities)
if ($rootScope.me.charities[i].id == $stateParams.charity) {
$scope.charity = $rootScope.me.charities[i];
for (var j in $rootScope.me.charities[i].campaigns)
if ($rootScope.me.charities[i].campaigns[j].id == $stateParams.campaign)
$scope.campaign = $rootScope.me.charities[i].campaigns[j];
}
$scope.buttonText = 'Save Changes';
$scope.saved = false;
$scope.savePage = function(){
$scope.campaign.details = jQuery('#desc').froalaEditor('html.get');
if( $scope.buttonText != 'Save Changes')
return;
$scope.buttonText = 'Please wait...';
$http.post('/api/website/charity/'+$stateParams.charity+'/campaign/'+$stateParams.campaign,$scope.campaign).then(function(response) {
if(response.data.success){
$scope.buttonText = 'Save Changes';
$rootScope.me = response.data.data;
jQuery('html, body').animate({scrollTop:0}, 400);
$scope.saved = true;
$timeout(function(){$scope.saved =false;},2000);
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
}
},function(){
$.notify('Error saving changes',{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
});
}
window.charity_id = $stateParams.charity;
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
}
]);App.controller('CharityLinksCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$scope.campaign = false;
for(var i in $rootScope.me.charities){
if($rootScope.me.charities[i].id == $stateParams.charity) {
$scope.charity = $rootScope.me.charities[i];
$scope.url = 'https://www.mycharityfund.ca/#/donate/'+$scope.charity.id;
for (var j in $rootScope.me.charities[i].campaigns)
if ($rootScope.me.charities[i].campaigns[j].id == $stateParams.campaign) {
$scope.campaign = $rootScope.me.charities[i].campaigns[j];
$scope.url = 'https://www.mycharityfund.ca/#/donate/' + $scope.charity.id+'/'+
$rootScope.slugify($scope.charity.name)+'/campaign/'+$scope.campaign.id+'/'
+$rootScope.slugify($scope.campaign.title);
}
}
}
if(!$scope.charity.public_name || !$scope.charity.public_name.length)
$scope.charity.public_name = $scope.charity.name;
if(!$scope.charity.public_phone || !$scope.charity.public_phone.length)
$scope.charity.public_phone = $scope.charity.phone_number;
$scope.amount = 50; //used for the links page
window.charity_id = $stateParams.charity;
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.title = 'Donate online';
$scope.target = '_blank';
$scope.style = '';
}
]);App.controller('CharityCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope', '$sce','$timeout',
function ($scope, $http, $stateParams, $state, $rootScope, $sce,$timeout) {
if ($stateParams.id == 52051) {
$state.go('home');
return;
}
$scope.charity_loading = true;
$http.get('/api/website/charity/'+$stateParams.id).then(function(response) {
$scope.charity = response.data.data;
$scope.charity_loading = false;
$scope.charity.address.postal_code = $scope.charity.address.postal_code.replace(/(.{3})/g,"$1 ");
//if($scope.charity.public_name != null)
// $scope.charity.name = $scope.charity.public_name;
if($scope.charity.public_phone != null && $scope.charity.public_phone != '')
$scope.charity.phone_number = $scope.charity.public_phone;
if($scope.charity.analytics_code != null)
gtag('config', $scope.charity.analytics_code);
$rootScope.metaservice.set("My Charity Fund - "+$scope.charity.name,"Donate online to "+$scope.charity.name+".",
$scope.charity.name+","+ $scope.charity.charity_number+","+$scope.charity.designation+", charity, tax receipt, canadian, donate","index, nofollow");
}, function(response){
if (response.status === 404) {
window.location.href = '/404';
return;
}
$scope.charity =false;
$scope.charity_loading = false;
});
$scope.isFavourite = false;
$scope.setIsFavourite = function(){
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($stateParams.id == $rootScope.me.favourites[i].id)
$scope.isFavourite = true;
}
$scope.setIsFavourite();
$timeout(function(){$scope.setIsFavourite();},500);
$timeout(function(){$scope.setIsFavourite();},2000);
$scope.addFavourite = function(){
if($scope.isFavourite)
return;
$rootScope.me.favourites.push($scope.charity);
$scope.isFavourite = true;
$http.post('/api/website/favourite/add/'+$stateParams.id);
}
$scope.removeFavourite = function(){
if(!$scope.isFavourite)
return;
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($stateParams.id == $rootScope.me.favourites[i].id)
$rootScope.me.favourites.splice(i,1);
$scope.isFavourite = false;
$http.post('/api/website/favourite/remove/'+$stateParams.id);
}
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
$scope.donateAsGuest = function(){
$http.defaults.headers.common.Authorization = 'Bearer None';
localStorage.removeItem('token');
$rootScope.me = false;
$state.go('donate',{id:$stateParams.id});
}
}
]);
App.controller('PasswordResetCtrl', ['$scope', '$rootScope', '$localStorage', '$http', '$state',
function ($scope, $rootScope, $localStorage, $http, $state) {
setTimeout(" if(typeof grecaptcha !== typeof undefined) mr.forms.captcha.renderWidgets ();",100);
$rootScope.metaservice.set("My Charity Fund - Password Reset","Reset your password if you can not login to your fund.","forgot, password, reset, login, charity, tax receipt, canadian, donate");
if($rootScope.me)
$state.go('dashboard');
$scope.sent = false;
$scope.updateAndLogin = function(){
$http.post('/api/website/recover2',{
email:$scope.email,
code:$scope.code,
password:$scope.password,
password2:$scope.password2
}).then(function(response) {
if(response.data.success){
$rootScope.doLogin(response.data.data.token,true);
}
else
$.notify(response.data,{globalPosition: 'top center'});
},function(response) {
for(i in response.data){
$.notify(response.data[i],{globalPosition: 'top center'});
break;
}
});
}
$scope.recover = function(){
if(grecaptcha.getResponse().length < 1){
return;
}
$http.post('/api/website/recover',{email:$scope.email}).then(function(response) {
if(response.data.success)
$scope.sent = true;
else
$.notify(response.data.data,{globalPosition: 'top center'});
},function(response) {
for(i in response.data){
$.notify(response.data[i],{globalPosition: 'top center'});
break;
}
});
}
}
]);App.controller('ManageCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope', '$timeout',
function ($scope, $http, $stateParams, $state, $rootScope, $timeout) {
for(i in $rootScope.me.accounts)
if($rootScope.me.accounts[i].id == $stateParams.account){
$scope.account = $rootScope.me.accounts[i];
$scope.account.send_single_tax_receipt_per_year = ''+$scope.account.send_single_tax_receipt_per_year;
$scope.account.newuser = {};
}
$scope.removeUser = function(id){
for(i in $scope.account.users)
if($scope.account.users[i].id == id)
$scope.account.users[i].deleted = true;
}
$scope.buttonText = 'Save Changes';
$scope.saveAccount = function(){
if( $scope.buttonText != 'Save Changes' && $scope.buttonText != 'Changes Saved')
return;
$scope.buttonText = 'Please wait...';
$http.post('/api/website/fund/'+$stateParams.account,$scope.account).then(function(response) {
if(response.data.success){
$rootScope.me = response.data.data;
//$state.go('dashboard');
$scope.buttonText = 'Changes Saved'
$timeout(function(){$state.go($state.current, {}, {reload: true});},2000);
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
}
},function(){
$.notify('Error saving changes',{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
});
}
}
]);App.controller('MissingCharityCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
setTimeout(" if(typeof grecaptcha !== typeof undefined) mr.forms.captcha.renderWidgets ();",100);
}
]);
App.controller('WithdrawalViewCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$http.get('/api/website/withdrawals/'+$stateParams.id).then(function(response) {
$scope.withdrawal = response.data.data;
});
}
]);
App.controller('HistoryCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
$scope.isGlobal = $stateParams.account == 'global';
$scope.funds = [];
if(!$scope.isGlobal){
for(i in $rootScope.me.accounts)
if($rootScope.me.accounts[i].id == $stateParams.account){
$scope.account = $rootScope.me.accounts[i]
}
}
else
for(j in $rootScope.me.accounts)
$scope.funds[$rootScope.me.accounts[j].id] = $rootScope.me.accounts[j].name;
$http.get('/api/website/history/'+$stateParams.account).then(function(response) {
$scope.history = response.data.data;
setTimeout(() =>
{ jQuery('#myTable').DataTable({
lengthMenu: [[10, 20, 50, 100, -1], [10, 20, 50,100,'All']],
'order': [[ 0, 'desc ']],
"columnDefs": [
{
"render": function ( data, type, row ) {
if(type == 'display')
return data.split(' ')[0];
return data;
},
"targets": 0
},{
"render": function ( data, type, row ) {
if(type == 'display') {
if(data == '')
return data;
data = parseFloat(data);
return data.toLocaleString('en-US', {style:'currency', currency:'USD'});
}
return data;
},
"targets": $scope.isGlobal ? [3,4] : [2,3]
}
],
dom: 'Blfrtip',
buttons: [
'copy',
{ extend: 'csv', title: 'Fund Transactions' },
{ extend: 'excel', title: 'Fund Transactions', customize: (xls) =>
{
let sheet = xls.xl.worksheets['sheet1.xml'];
let styles = xls.xl['styles.xml'];
const lastXfIndex = $('cellXfs xf', styles).length - 1;
const lastFontIndex = $('fonts font', styles).length - 1;
const leadingDollar = 300;
let f1 = `
`;
styles.childNodes[0].childNodes[1].innerHTML += f1;
const boldUnderline = lastFontIndex + 1;
styles.childNodes[0].childNodes[0].innerHTML += ``;
let s1 = `
`;
styles.childNodes[0].childNodes[5].innerHTML += s1;
const withLeadingDollar = lastXfIndex + 1;
const centeredBold = lastXfIndex + 2;
let cell = $('c[r=A1]', sheet).attr('s', centeredBold);
$('row c[r^="C"]', sheet).attr('s', withLeadingDollar);
$('row c[r^="D"]', sheet).attr('s', withLeadingDollar);
}},
{ extend: 'print', title: 'Fund Transactions' }
]
});
}, 500);
});
}
]);
App.controller('RegisterCtrl', ['$scope', '$localStorage', '$http', '$state','$rootScope',
function ($scope, $localStorage, $http, $state, $rootScope) {
$rootScope.metaservice.set("My Charity Fund - Register","Create an account to manage your funds.","register, sign up, charity, tax receipt, canadian, donate");
$scope.buttonText = 'Next';
$scope.registerAccount = function(){
if( $scope.buttonText != 'Next')
return;
$scope.buttonText = 'Please wait...';
$http.post('/api/website/register',$scope.register).then(function(response) {
if(response.data.success){
$rootScope.doLogin(response.data.data.token,true);
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Next';
}
},function(response) {
for(i in response.data){
$.notify(response.data[i][0],{globalPosition: 'top center'});
$scope.buttonText = 'Next';
break;
}
});
}
}
]);App.controller('CharityPageCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope','$sce','$timeout','$filter',
function ($scope, $http, $stateParams, $state, $rootScope, $sce,$timeout,$filter) {
for(var i in $rootScope.me.charities){
if($rootScope.me.charities[i].id == $stateParams.charity) {
$scope.charity = $rootScope.me.charities[i];
if (!$scope.charity.address)
$scope.charity.address = {};
}
}
if(!$scope.charity.public_name || !$scope.charity.public_name.length)
$scope.charity.public_name = $scope.charity.name;
if(!$scope.charity.public_phone || !$scope.charity.public_phone.length)
$scope.charity.public_phone = $scope.charity.phone_number;
if($scope.charity.description == null || !$scope.charity.description.length){
$scope.charity.description = ''+$scope.charity.name+' is a ';
if( $scope.charity.category.substr(-1) == 's')
$scope.charity.description += $scope.charity.category.substring(0, $scope.charity.category.length - 1).replace(' Charitie','').replace('Activitie','Activity');
else
$scope.charity.description += $scope.charity.category
$scope.charity.description += ' Charity located in '+$filter('ucwords')($scope.charity.address.city)+', '+$filter('ucwords')($scope.charity.address.province)+'
';
if($scope.charity.cra_description && $scope.charity.cra_description.length)
$scope.charity.description += 'Services Provided by '+$scope.charity.name+'
'+$scope.charity.cra_description;
}
$scope.buttonText = 'Save Changes';
$scope.saved = false;
$scope.savePage = function(){
if($state.current.name == 'charity-design')
$scope.charity.description = jQuery('#desc').froalaEditor('html.get');
if( $scope.buttonText != 'Save Changes')
return;
$scope.buttonText = 'Please wait...';
$http.post('/api/website/charity/'+$stateParams.charity,$scope.charity).then(function(response) {
if(response.data.success){
$scope.buttonText = 'Save Changes';
$rootScope.me = response.data.data;
jQuery('html, body').animate({scrollTop:0}, 400);
$scope.saved = true;
$timeout(function(){$scope.saved =false;},2000);
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
}
},function(){
$.notify('Error saving changes',{globalPosition: 'top center'});
$scope.buttonText = 'Save Changes';
});
}
window.charity_id = $stateParams.charity;
if($state.current.name == 'charity-design'){
setTimeout(" var dz = jQuery('#dropzone').dropzone({\
url: '/api/website/charity-logo/'+ window.charity_id,\
headers: { 'Authorization': localStorage.token } ,\
init: function() {\
this.on('success', function(file) {\
var response = JSON.parse(file.xhr.response);\
jQuery('#logoImg').attr('src',response.data);\
});\
}\
});",1500);
}
$scope.to_trusted = function(html_code) {
return $sce.trustAsHtml(html_code);
}
console.log($state);
}
]);App.controller('StatementCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope',
function ($scope, $http, $stateParams, $state, $rootScope) {
for(i in $rootScope.me.accounts)
if($rootScope.me.accounts[i].id == $stateParams.account){
$scope.account = $rootScope.me.accounts[i];
}
function setDate(name, value)
{
$scope[name] = moment(value).format('DD MMMM, YYYY');
};
$('.datepicker#start').pickadate({ format: 'dd mmm', onSet: (c) => setDate('start', c.select) });
$('.datepicker#end').pickadate({ format: 'dd mmm', onSet: (c) => setDate('end', c.select) });
$scope.buttonText = 'Generate Statement';
$scope.generateStatement = function(){
if( $scope.buttonText != 'Generate Statement')
return;
$scope.buttonText = 'Processing, please wait...';
$http.post('/api/website/statement/'+$stateParams.account,{start_date: $scope.start, end_date: $scope.end}).then(function(response) {
if(response.data.success){
//window.location = '/pdfs/'+response.data.data.file+'.pdf';
$scope.buttonText = 'Generate Statement';
window.open('/pdfs/'+response.data.data.file+'.pdf', '_blank');
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Generate Statement';
}
},function(){
$.notify('Error generating statement',{globalPosition: 'top center'});
$scope.buttonText = 'Generate Statement';
});
}
}
]);
App.controller('WithdrawalCtrl', ['$scope', '$http', '$stateParams', '$state', '$rootScope', '$timeout',
function ($scope, $http, $stateParams, $state, $rootScope,$timeout) {
$scope.account_id = false;
$scope.account = false;
$scope.canSelectFund = false;
$scope.charitySelector = 'search';
$scope.account_withdrawal = {account_id:false,charity_id:'',dedication:'in honour of', privacy_level: 'name email and address'};
$scope.isFavouriteCharitySelector = false;
$scope.initWithdrawal = function(){
if(!$rootScope.me){
$timeout($scope.initWithdrawal,50);
return;
}
$scope.isFavouriteCharitySelector = $rootScope.me.favourites.length;
if($stateParams.account)
$scope.account_id = $stateParams.account;
else if( $rootScope.me.accounts.length == 1)
$scope.account_id =$rootScope.me.accounts[0].id;
else{
$scope.canSelectFund = true;
if($rootScope.me.accounts.length)
$scope.account_id =$rootScope.me.accounts[0].id;
}
if(!$scope.account_id)
$state.go('dashboard');
for(i in $rootScope.me.accounts)
if($rootScope.me.accounts[i].id == $scope.account_id){
$scope.account = $rootScope.me.accounts[i]
$scope.account_withdrawal.privacy_level = $rootScope.me.accounts[i].privacy_level;
$scope.account_withdrawal.account_id = $rootScope.me.accounts[i].id;
}
$scope.memo_self = $rootScope.me.precheck_memo_self > 0;
$scope.memo = $rootScope.me.precheck_memo_charity > 0;
$scope.dedicate = $rootScope.me.precheck_dedicate > 0;
/*for(i in $rootScope.me.recent.withdrawals)
if($rootScope.me.recent.withdrawals[i].account_id == $scope.account_id )
$scope.charitySelector = 'recent';
if($scope.charitySelector == '')
*/
$scope.charitySelector = 'search';
};
$scope.initWithdrawal();
$scope.charity = false;
if($stateParams.charity) {
$scope.charityFixed = true;
$scope.account_withdrawal.charity_id = $stateParams.charity;
$scope.charity = {name:''};
$http.get('/api/website/charity/'+$stateParams.charity).then(function(response) {
$scope.charity = response.data.data;
if($scope.charity.is_revoked > 0)
$state.go('charity',{id:$stateParams.charity, name: $rootScope.slugify($scope.charity.name)});
});
}
else
$scope.charityFixed = false;
$scope.campaignFixed = false;
$scope.amountFixed = false;
if($rootScope.donateStateParams){ //logged in user clicked a public donation link for a specific charity or campaign
if($rootScope.donateStateParams.campaign){
$scope.campaignFixed = true;
$scope.account_withdrawal.charity_campaign_id = $rootScope.donateStateParams.campaign;
}
if($rootScope.donateStateParams.amount){
$scope.amountFixed = true;
$scope.account_withdrawal.amount = $rootScope.donateStateParams.amount;
}
$rootScope.donateStateParams = false;
}
var icon;
setTimeout(function(){
jQuery('input#charity').flexdatalist({
cache:false,
normalizeString: function (string) {
return string.replace("'",''); //ignore ' in searches so "bnai" will return "b'nai" and vice versa
}
});
icon = $('i.icon.icon-Magnifi-Glass2');
$('input#charity').on('before:flexdatalist.data', function() {
icon.addClass('fa-spin');
});
$('input#charity').on('after:flexdatalist.data', function() {
icon.removeClass('fa-spin');
});
},100);
$scope.ecard = false;
$scope.buttonText = 'Next';
$scope.confirmRecurring = function(type) {
if ($scope.account_withdrawal.recurring) {
var message = 'You have chosen to make this ' + type + ' recur monthly. If this is not what you intended, press cancel.';
if (!confirm(message)) {
$scope.account_withdrawal.recurring = false;
}
}
};
$scope.$watch('account_withdrawal.charity_id', function(newValue, oldValue) {
if(parseInt(newValue) > 0)
$http.get('/api/website/charity/'+$scope.account_withdrawal.charity_id).then(function(response) {
$scope.charity = response.data.data;
$scope.isFavourite = false;
for(i in $rootScope.me.favourites)
if($scope.charity.id == $rootScope.me.favourites[i].id)
$scope.isFavourite = true;
});
});
$scope.$watch('account', function(newValue, oldValue) {
$scope.account_withdrawal.privacy_level = newValue.privacy_level;
});
$scope.editDonation = function(){
$scope.buttonText = 'Next';
}
$scope.makeDonation = function(){
if( $scope.buttonText != 'Next' && $scope.buttonText != 'Confirm Donation'){
return; //processing donation
}
if( $scope.buttonText == 'Next'){
$scope.account_withdrawal.amount = $scope.account_withdrawal.amount.replace(/[^0-9.]/g, ''); //clean amount field
$scope.buttonText = 'Confirm Donation';
$('html,body').animate({ scrollTop: 0 }, 'normal');
return;
}
if($scope.account)
$scope.account_withdrawal.account_id = $scope.account.id;
$scope.account_withdrawal.prechecks = {
'precheck_memo_self': $rootScope.me.precheck_memo_self,
'precheck_memo_charity' : $rootScope.me.precheck_memo_charity,
'precheck_dedicate' : $rootScope.me.precheck_dedicate,
};
$scope.buttonText = 'Processing Donation, please wait...';
$http.post('/api/website/withdrawal',$scope.account_withdrawal).then(function(response) {
if(response.data.success){
$rootScope.me = response.data.data;
$state.go('thanks-fund');
}
else{
$.notify(response.data.data,{globalPosition: 'top center'});
$scope.buttonText = 'Next';
}
},function(){
$.notify('Error processing donation',{globalPosition: 'top center'});
$scope.buttonText = 'Next';
});
}
//favourites
$scope.isFavourite = false;
$scope.addFavourite = function(){
if($scope.isFavourite)
return;
$rootScope.me.favourites.push($scope.charity);
$scope.isFavourite = true;
$http.post('/api/website/favourite/add/'+$scope.charity.id);
}
$scope.removeFavourite = function(){
if(!$scope.isFavourite)
return;
if($rootScope.me)
for(i in $rootScope.me.favourites)
if($scope.charity.id == $rootScope.me.favourites[i].id)
$rootScope.me.favourites.splice(i,1);
$scope.isFavourite = false;
$http.post('/api/website/favourite/remove/'+$scope.charity.id);
}
}
]);
App.controller('CharityPaymentDetailsCtrl',['$scope', '$http', '$stateParams', '$state', '$rootScope','$timeout', '$sce',
function ($scope, $http, $stateParams, $state, $rootScope, $timeout, $sce) {
// Get charity data from rootScope
for(var i in $rootScope.me.charities){
if($rootScope.me.charities[i].id == $stateParams.charity) {
if($rootScope.me.charities[i].started_vopay_onboarding) {
$timeout(function() {
window.location.reload();
}, 100);
}
$scope.charity = $rootScope.me.charities[i];
console.log($scope.charity);
}
}
$scope.disableGetStarted = false;
// Trusted URL filter for iframe
$scope.trusted = function(url) {
return $sce.trustAsResourceUrl(url);
};
$scope.getStarted = function () {
if($scope.disableGetStarted)
return;
$scope.disableGetStarted = true;
$http.post('/api/website/charity-eft/get-iframe',{'charity_id':$scope.charity.id}).then(function(response) {
if(response.data.success) {
// Add iframe to view with the EmbedURL
$scope.embedURL = response.data.EmbedURL;
$scope.iframeKey = response.data.IframeKey;
$scope.showIframe = true;
for(var i in $rootScope.me.charities){
if($rootScope.me.charities[i].id == $stateParams.charity) {
$rootScope.me.charities[i].started_vopay_onboarding = true;
}
}
} else {
$.notify(response.data.data || 'Error getting started', {globalPosition: 'top center'});
$scope.disableGetStarted = false;
}
}, function() {
$.notify('Error getting started', {globalPosition: 'top center'});
$scope.disableGetStarted = false;
});
}
}
]);
const depositFormCaptcha = {
_widgetId: '',
_divId: 'captcha',
_siteKey: '6LcnZz4UAAAAADM_lV5XN0MbptF0fEZ3L8e8JvY8',
create: function () {
typeof grecaptcha == 'undefined' && !jQuery('script[src*="recaptcha/api.js"]').length
? this.load()
: this.render()
},
load: function () {
const $script = jQuery('