/**
 * JavaScript Application Controller Utility to provide the ability to switch between Communities (NA & EU) 
 * Provides Various Utility Functions
 * JS Remoting methods to CommunityBase.
 * Logging Functionality.
 * 
 */
var CommunityJSApp = CommunityJSApp || (function() {
           // Logging features to log the messages to the Console. 
           // Set Debug = true to display the messages in Production
           // If Error, will log to the Console. Prefix is Community VF
           var log = {
               prefix: 'Community VF: ',
               info: function(msg, obj) {
                   msg = this.prefix + msg;
                   if (console && console.log && console.groupCollapsed && console.groupEnd) {
                       if (obj) {
                           console.groupCollapsed(msg);
                           console.log(JSON.stringify(obj, undefined, 2));
                           console.groupEnd();
                       } else {
                           console.log(msg);
                       }
                   }
               },
               debug: function(msg, obj) {
                   if (CommunityJSApp && CommunityJSApp.debug && CommunityJSApp.debug == true) this.info(msg, obj);
               },
               error: function(msg, obj) {
                   if (console && console.error) {
                       console.error(msg, obj);
                   }
               }
           },
           // Register the Handlers, Identify the Communities and based on the Community hide the respective components of the page
           // EU Classes to hide - EUCommunityComponent
           // NA Classes to hide - NACommunityComponent
           // Refresh the page with setting community URL param.
           registerHandlers = function(browser_locale) {
             
               log.debug('Inside Registration', globalCommunityName);
        
               var language = getParameterByName('lang');
               var cntry    = getParameterByName('cntry');
               var fallbackLocale = getParameterByName('fbLocale');

               if (globalCommunityName && globalCommunityName == 'NA') {

                   // Hide the components that are not required to be displayed for NA Community
                   $('#naCommunity, #langDD').remove();
                    $('.NACommunityComponent').show();
                    $('.EUCommunityComponent').each(function(){
                       $(this).hide();
                      });


                   $(document).on('click','#euCommunity',function(e){
                       e.preventDefault();
                       globalCommunityName = 'EU';
                       window.location.href = '?community='+globalCommunityName;
                   });

                   $(document).on('click','.naCommunityBtn',function(e){
                       e.preventDefault();

                       var url = $(this).attr("href");
                       globalCommunityName = 'NA';

                       log.debug('naCommunityBtn Clicked', url);

                       if (url.indexOf('?') != -1)
                           window.location.href = url + '&community='+globalCommunityName;
                       else
                           window.location.href = url + '?community='+globalCommunityName;
                   });


               } else if (globalCommunityName && globalCommunityName == 'EU') {

                   $('#euCommunity').remove();

                   $('.EUCommunityComponent').show();
                   $('.NACommunityComponent').each(function(){
                       $(this).hide();
                   });

                   displayPage();

                   $(document).on('click','#naCommunity',function(e){
                       e.preventDefault();
                       globalCommunityName = 'NA';
                       window.location.href = '?community='+globalCommunityName;
                   });

               }
           },
           // Load the Default Community and store in Cookies after the JS Remoting Call to the method.
           loadDefaultCommunity = function() {

               log.debug('Inside Load', globalCommunityName);
               // JS Remoting to call the Community Defaults
               BDEU_CommunityTemplateCon.getCommunityDefaults(globalCommunityName, function(result,event){
                    if (event.status && result && !result.errors) {

                   log.debug('After Remoting', result);

                   Cookies.set("lang",result.defaultLanguage);
                   Cookies.set("cntry",result.defaultCountry);
                   Cookies.set("fbLocale",result.fallbackLanguage);
                  
                   log.debug('Current Profile',CommunityJSApp.currentProfileId);

                   if (result.defaultProfile.Id == CommunityJSApp.currentProfileId) {
                      isAuthenticated = true;   
                   }

                   // Initialize the Components that are loaded by the page
                   initComponents();
                   log.debug('Theme Profile',globalCommunityName);

                   // Apply the theme
                    applyTheme();
					googleAnalyticsTracking(result.GoogleAnalyticsTrackingID);

                 } else {
                   log.debug('Remoting Error', event);
                   displayPage();
                 }
               });
           },
           // Initialize the Components, 
           // Add required classes for the NA Community to the elements.
           initComponents = function(){
                // Navigation Component.
               var country = Cookies.get("cntry");
               log.debug('Init Components - Country', country);
               
               if (typeof country == 'undefined' || country == null) {
                   loadDefaultCommunity();
                   country = Cookies.get("cntry");
               }

               $('.iconCls').addClass('ico_'+country);
               $('.iconCls').after(country);

               // Set the ones with Authenticated States to True.
               if (isAuthenticated) {

                  $('.AuthenticatedState').each(function(){
                       $(this).show();
                  });
                  
                  $('.UnauthenticatedState').each(function(){
                       $(this).hide();
                  });
               }

           },
            applyTheme= function() {
              if (isAuthenticated) {

                  var userId = '{!$User.Id}';
                  var themeId = null;
                  
                  if (currentTheme == null || typeof currentTheme == 'undefined') {
                      BDEU_CommunityTemplateCon.getMemberTheme(userId,themeId,function(result,event){
                            
                             log.debug('currentTheme', userId, result);
                            if (result == null) {
                              currentTheme = 'default';
                              displayPage();
                            } else { 
                              currentTheme = result;
                              themeChange(currentTheme);
                            }
                      });
                  } else if (currentTheme != 'default'){
                      themeChange(currentTheme);
                  }
                  log.debug('currentThme', currentTheme);

              } else {
                  displayPage();
              }
            },
            themeChange = function(theme) {
                // Set the defaults.
                console.log('theme change', theme);
                if (theme.Community_Type__r.MasterLabel == 'EU') {
                   
                    if (globalCommunityName && globalCommunityName == 'EU') {
                        //Secondary Logo   - these logos either have a 100px height or a 200px height. if 200px, apply additional classes to handle placement of taller logos
                        var euClientLogoSrc = $('#euClientLogo').attr('src') + theme.Logo_URL__c;
                        $('#euClientLogo').attr('src', euClientLogoSrc);
                        var img = new Image();
                        img.onload = function() {
                           if (this.height>100) {
                                $('.eu_client_logo').addClass('eu_client_logo_tall');
                           } else if (this.width>240) {
                                $('.eu_client_logo').addClass('eu_client_logo_wide');
                           } else {
                                $('.eu_client_logo').addClass('eu_client_logo_standard');
                           }
                           $('.eu_client_logo').show();
                        }
                        img.src = euClientLogoSrc;

                        console.log('src', euClientLogoSrc);
                      
                    }
                } else {
                  var primary_color     = '#a2a6a9';
                  var secondary_color   = '#af9c65';
                  var navbar_bg_color   = '#005696';
                  var navbar_link_color = '#a1c1d8';
                  var body_bg_color     = '#f2f2f2';
                  var text_color        = '#a2a6a9';
                  var link_color        = '#005696';
                  var brand_image       = defaultImage;
                  
                  // Set the theme colors.
                  if (typeof theme.Brand_Primary__c != 'undefined' && theme.Brand_Primary__c != null)
                      primary_color = theme.Brand_Primary__c;
                  if (typeof theme.Brand_Secondary__c != 'undefined' && theme.Brand_Secondary__c != null)  
                      secondary_color = theme.Brand_Secondary__c;
                  if (typeof theme.Navbar_Background_Color__c != 'undefined' && theme.Navbar_Background_Color__c != null)  
                      navbar_bg_color = theme.Navbar_Background_Color__c;
                  if (typeof theme.Navbar_Link_Color__c != 'undefined' && theme.Navbar_Link_Color__c != null)      
                      navbar_link_color = theme.Navbar_Link_Color__c;
                  if (typeof theme.Body_Background_Color__c != 'undefined' && theme.Body_Background_Color__c != null)      
                      body_bg_color = theme.Body_Background_Color__c;
                  if (typeof theme.Text_Color__c != 'undefined' && theme.Text_Color__c != null)      
                      text_color = theme.Text_Color__c;
                  if (typeof theme.Link_Color__c != 'undefined' && theme.Link_Color__c != null)      
                      link_color = theme.Link_Color__c;
                  if (typeof theme.Logo_URL__c != 'undefined' && theme.Logo_URL__c != null)      
                      brand_image = theme.Logo_URL__c;
                  
                  $('body').css("color",text_color);
                  $('body').css("background-color",body_bg_color);
                  //$('a').css('color',link_color);
                  brand_image = $('.navbar-bestdoctors .navbar-brand').attr("data-logo") + brand_image;
                  var img = new Image();
                  img.onload = function() {
                     if (this.height>46) {
                          $('.navbar-bestdoctors .navbar-brand').css("background-size", "auto 46px");
                     } else if (this.width>240) {
                          $('.navbar-bestdoctors .navbar-brand').css("width", "240px");;
                     } 
                  }
                  img.src = brand_image;

                  $('.navbar-bestdoctors .navbar-brand').css('background-image','url(' + brand_image + ')', 'important');
                  $('.navbar-bestdoctors .navbar-brand').css('background-repeat','no-repeat');
                  $('.navbar-bestdoctors').css('background-image','linear-gradient(to bottom,'+navbar_bg_color+' 0,'+navbar_bg_color +' 100%)', 'important');
                  $('.container .jumbotron').css('background-color',primary_color, 'important');
                  $('.navbar-bestdoctors-invert .dropdown-menu').css('background-color',primary_color, 'important');
                  
                  $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-form').css('background-color',secondary_color, 'important');
                  $('.floatingFooterBottom .liveAgent').css('background-color',secondary_color, 'important');
                  $('.bg_light').css('background-color',lightenDarkenColor(secondary_color,50));
                  $("<style type='text/css'> .bg_light.override:after{background-color:"+lightenDarkenColor(secondary_color,50)+";} </style>").appendTo("head");

                  $('.bg_light').addClass('override');

                  $('.register_sidebar').css('background-color',lightenDarkenColor(secondary_color,50));
                  $('.bg_light.open_menu:after').css('background-color',lightenDarkenColor(secondary_color,50));

                  $('.jumbotron h3').css('color',text_color);
                  $('#sidebar_content h2').css('color',text_color);

                  // $('.navbar-bestdoctors').css('background-color',primary_color, 'important');
                  // $('.carousel-indicators .active').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors-invert .dropdown-menu').css('background-color',primary_color, 'important');
                  // $('.buscador_sintomas .btn-blue-round').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors-invert .navbar-nav > .open > a').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors-invert .navbar-nav > .open > a:hover').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors-invert .navbar-nav > .open > a:focus').css('background-color',primary_color, 'important');
                  // $('.btn-blue-round').css('background-color',primary_color);
                  // $('.well.buscador_sintomas .btn-blue-round').css('background-color',primary_color);
                  // $('.btn-light.btn-blue').css('background-color',primary_color);
                  // $('.table thead > tr > th').css('background-color',primary_color);
                  // $('.btn-bestdoctors-bl').css('background-color',primary_color);
                  // $('.navbar-bestdoctors .navbar-nav > .dropdown.active > a').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors .navbar-nav > .dropdown.active > a:hover').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors .navbar-nav > .dropdown.active > a:focus').css('background-color',primary_color, 'important');
                  // $('.jumbotron.dark').css('background-color',primary_color, 'important');
                  // $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-nav > .dropdown.active > a').css('background-color',text_color, 'important');
                  // $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-nav > .dropdown.active > a:hover').css('background-color',text_color, 'important');
                  // $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-nav > .dropdown.active > a:focus').css('background-color',text_color, 'important');
                  // $('.mapa_web .nav-tabs > li.active > a').css('background-color',text_color, 'important');
                  // $('.mapa_web .nav-tabs > li.active > a:hover').css('background-color',text_color, 'important');
                  // $('.mapa_web .nav-tabs > li.active > a:focus').css('background-color',text_color, 'important');

                  // $('.navbar-bestdoctors').css('background-color',navbar_bg_color, 'important');
                  // $('.container .jumbotron','#carousel-sidebar-home','.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-form').css('background-color',secondary_color, 'important');
                  // $('.navbar-form navbar-right','.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-form','.dropdown-menu > li > a:hover','.dropdown-menu > li > a:focus','.dropdown-menu > .active > a','.dropdown-menu > .active > a:hover','.dropdown-menu > .active > a:focus','.container .jumbotron','.btnMenu','.nav.navbar-nav .dropdown-menu > li.active > a','.nav.navbar-nav .dropdown-menu > li:hover > a','.navbar-collapse').css('background-color',secondary_color, 'important');
                  
                  
                  // $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-form','.jumbotron .dropdown-menu li a:hover','.jumbotron .dropdown-menu li a:focus .jumbotron .dropdown-menu .active a','#carousel-sidebar-home').css('background-color',secondary_color);
                  // $('.navbar-bestdoctors.navbar-bestdoctors-invert .navbar-form','.jumbotron .dropdown-menu li a:hover','.jumbotron .dropdown-menu li a:focus .jumbotron .dropdown-menu .active a','#carousel-sidebar-home').css('background-image','-webkit-linear-gradient(top, '+secondary_color+', 100%, '+secondary_color+', 100%)');
                }
                displayPage();
           },
           displayPage = function() {
             $('.brandedContainer').show();
           },
           /* Util Functions*/
           toObject = function(arr) {
               if (!$.isArray(arr)) return arr;
               var rv = {};
               for (var i = 0; i < arr.length; ++i)
                   if (arr[i] !== undefined) rv[arr[i]] = null;
               return rv;
           },
           getParameterByName = function(name, url) {
               if (!url) {
                 url = window.location.href;
               }
               name = name.replace(/[\[\]]/g, "\\$&");
               var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                   results = regex.exec(url);
               if (!results) return null;
               if (!results[2]) return '';
               return decodeURIComponent(results[2].replace(/\+/g, " "));
           },
           // Switch Framework to enable or disable the functionality based on Hierarchy Custom Settings
           // JS Remoting to get the Switches. 
           switchFramework = function() {
              BDEU_CommunityTemplateCon.getSwitches(function(result,event){
                 if (event.status && result && !result.errors) {

                   log.debug('After Remoting Switches', result);
                   // Enable or Disable Functionality.
                   enableDisable(result);
                  
                 } else {
                   log.debug('Remoting Error', event);
                 } 
              });
           },
           lightenDarkenColor = function (col, amt) {
                var usePound = false;
                if (col[0] == "#") {
                  col = col.slice(1);
                  usePound = true;
                }
                var num = parseInt(col, 16);
                var r = (num >> 16) + amt;
                if (r > 255) {
                  r = 255;
                } else if (r < 0) {
                  r = 0;
                }
                var b = ((num >> 8) & 0x00FF) + amt;
                if (b > 255) {
                  b = 255;
                } else if (b < 0) {
                  b = 0;
                }
                var g = (num & 0x0000FF) + amt;
                if (g > 255) {
                  g = 255;
                } else if (g < 0) {
                  g = 0;
                }
                return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
            },
           // Enable or Disable functionality based on the Switches.
           enableDisable = function(configs) {
              if (!configs.Enable_NA_Community__c)
                  $('#communitySwitcher').remove();
           },
		   googleAnalyticsTracking = function(TrackingId) { 
		       if(TrackingId != null || TrackingId != '') {
				    try{
					  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
					  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
					  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
					  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
					  ga('create',TrackingId, 'auto');
					  ga('send', 'pageview');
					}
					catch(err){
						log.debug('Google Analytics Tracking exception',event);
					}
			   }
			   else {
				    log.debug('Google Analytics Id Not Found', event);
			   }
		   };
           return {
               registerHandlers: registerHandlers,
               loadDefaultCommunity: loadDefaultCommunity,
               initComponents: initComponents,
               displayPage: displayPage,
               // utils
               debug: false,
               currentProfileId: null, // Adding Profile Id for Comparison
               switchFramework: switchFramework,
               toObject: toObject,
               getParameterByName: getParameterByName,
               log: log
           };

       }());