// *************************************************************************
// *                                                                       *
// * (c) 2008-2011 Wolf Software Limited <support@wolf-software.com>       *
// * All Rights Reserved.                                                  *
// *                                                                       *
// * This program is free software: you can redistribute it and/or modify  *
// * it under the terms of the GNU General Public License as published by  *
// * the Free Software Foundation, either version 3 of the License, or     *
// * (at your option) any later version.                                   *
// *                                                                       *
// * This program is distributed in the hope that it will be useful,       *
// * but WITHOUT ANY WARRANTY; without even the implied warranty of        *
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
// * GNU General Public License for more details.                          *
// *                                                                       *
// * You should have received a copy of the GNU General Public License     *
// * along with this program.  If not, see <http://www.gnu.org/licenses/>. *
// *                                                                       *
// *************************************************************************

(function($)
{
  $.jpecrga = function(options)
    {

      var defaults = {
                       gaKey:                    '',
                       backgroundColor:          '#fff',
                       permanentBackgroundColor: '#bbffbb',
                       borderColor:              '#000',
                       textColor:                '#444',
                       message:                  'Burson-Marsteller.co.uk would like to use cookies to store information on your computer. We use these to aid in improving and maintaining our website.<br />Find more info by reading our <a href="/privacy-policy/">privacy policy</a>. <br /> <strong>Do you consent to receiving cookies from our website?</strong>',
                       messageHasCookie:                  'You have chosen not to let Burson-Marsteller store cookies on your computer. (more info: <a href="/privacy-policy/">privacy policy</a>) If you do consent to receiving cookies click "',
                       permanentMessage:         'Would you like us to save your preference permanently? We will remember this preference using a cookie on your machine.',
                       moreInfo:	         '',
                       permanentMoreInfo:        '',
                       noConsentCallback:        null
                    };

      var options = $.extend(defaults, options);

      if (!(options.gaKey) || !(options.gaKey.length))
        {
          alert("Missing GA Key!");
          return;
        }

      cookieConsent();

      function cookieConsent()
        {
          var sessionCookieName = 'BM_cookie_notification';
          var permanentCookieName = 'BM_cookie_notification';

          var hasConsent = cookiesHasConsent(); 
          var hasPermanentConsent = cookiesHasPermanentConsent(); 

          var yesCallback = function () {cookiesClickedYes()};
          var noCallback = function () {cookiesClickedNo()};
          var yesPermanentCallback = function () {cookiesClickedYesPermanent()};
          var noPermanentCallback = function () {cookiesClickedNoPermanent()};

          var backgroundColor = options.backgroundColor;
          var permanentBackgroundColor = options.permanentBackgroundColor;
          var borderColor = options.borderColor;
          var textColor = options.textColor;
		  
          var step = 0;
          var gaInserted = false;

          var answer = '';

          if (hasPermanentConsent != null)
            {
              hasConsent = hasPermanentConsent;
            }

          if (hasConsent == null)
            {
              var messageDiv = $('<div />');
              var messagePara = $('<p>' + options.message + '</p>');
              var responseForm = $('<div />');
              var yesButton = $('<input id="ck-yes" type="submit" name="yes" value="Yes" />');
              var noButton = $('<input id="ck-no" type="submit" name="no" value="No" />');

              var moreInfoDiv = $('<div>' + options.moreInfo + '</div>');

              messageDiv.css('background-color', backgroundColor);
              messageDiv.css('color', textColor);
              messageDiv.css('position', 'absolute');
              messageDiv.css('top', '0px');
              messageDiv.css('left', '-60px');
              messageDiv.css('padding', '5px 30px 32px');
              messageDiv.css('vertical-align', 'middle');
              messageDiv.css('border', '3px solid ' + borderColor);
			  messageDiv.css('border-top', '0px');
              messageDiv.css('font-size', '13px');
              messageDiv.css('font-family', 'Arial, Helvetica, Sans-Serif');
              messageDiv.css('z-index', '9999');
              //messageDiv.css('box-shadow', '0px 0px 5px #000');
			  messageDiv.css('width', '1006px');

              messagePara.css('margin', '0px');
              messagePara.css('padding', '0px');
              messagePara.css('line-height', '16px');
              messagePara.css('font-size', '1.0em');

              responseForm.css('position', 'absolute');
              responseForm.css('top', '57px');
              responseForm.css('left', '30px');
              responseForm.css('width', '100px');

              yesButton.css('margin-right', '10px');
              yesButton.css('background', '#fff');
			  yesButton.css('border', '1px solid #000');
			  yesButton.css('font-size', '1.0em');
			  yesButton.css('width', '40px');
			  yesButton.css('font-weight', 'bold');

              noButton.css('background', '#fff');
			  noButton.css('border', '1px solid #000');
			  noButton.css('font-size', '1.0em');
			  noButton.css('width', '40px');
			  noButton.css('font-weight', 'bold');

              moreInfoDiv.css('background-color', backgroundColor);
              moreInfoDiv.css('color', textColor);
              moreInfoDiv.css('position', 'fixed');
              moreInfoDiv.css('left', '20px');
              moreInfoDiv.css('right', '20px');
              moreInfoDiv.css('padding', '7px 10px 7px 10px');
              moreInfoDiv.css('vertical-align', 'middle');
              moreInfoDiv.css('border', '1px solid ' + borderColor);
              moreInfoDiv.css('border-top', 'none');
              moreInfoDiv.css('font-size', '12px');
              moreInfoDiv.css('font-family', 'Arial, Helvetica, Sans-Serif');
              moreInfoDiv.css('z-index', '9998');
              moreInfoDiv.css('display', 'none');
              moreInfoDiv.css('border-radius', '0px 0px 10px 10px');
              moreInfoDiv.css('-moz-border-radius', '0px 0px 10px 10px');
              moreInfoDiv.css('box-shadow', '0px 0px 5px #000');

              responseForm.append(yesButton);
              responseForm.append(noButton);

              messageDiv.append(messagePara);
              messageDiv.append(responseForm);

              $('#wrapper').append(messageDiv);
              $('#wrapper').append(moreInfoDiv);

              var origHeight = messageDiv.height();

              messageDiv.css('display', 'none');
              messageDiv.fadeIn(400);

              yesButton.click( function()
                {
                  //hideMoreInfo();
                      answer = true;
                      yesCallback();
					  yesPermanentCallback();
					  hideDiv();
                     // nextStep();
                });

              noButton.click( function ()
                {
                  hideMoreInfo();
                      answer = false;
                      noCallback();
                      if (options.noConsentCallback != null) {
                        options.noConsentCallback();
                      }
					  yesPermanentCallback();
                      hideDiv();
                });

         /*     function nextStep()
                {
                  messageDiv.fadeOut(200, function()
                    {
                      //messageDiv.css('display','none !important' );
                      //messagePara.html(options.permanentMessage + ' <a href="#">More Info</a>');
                      //moreInfoDiv.html(options.permanentMoreInfo);
                      //bindMoreInfo();
                      //messageDiv.fadeIn(200);
                    });
                  step++;
                }
*/
              function hideDiv()
                {
                  messageDiv.fadeOut(400, function()
                    {
                      messageDiv.remove()
                    });
		}
            }
          else if (hasConsent == true)
            {
              insertGA();
            }
          else if (hasConsent == false)
            {
			  
              var messageDiv = $('<div />');
              var messagePara = $('<p>' + options.messageHasCookie+'</p>');
              var responseForm = $('<div />');
              var yesButton = $('<a href="javaScript:void();" id="yesButton">yes</a>');
              //var yesButton = $('#yesButton');
              //var noButton = $('<input id="ck-no" type="submit" name="no" value="No" />');

              var moreInfoDiv = $('<div>' + options.moreInfo + '</div>');

              messageDiv.css('background-color', backgroundColor);
              messageDiv.css('color', textColor);
              messageDiv.css('position', 'absolute');
              messageDiv.css('top', '0px');
              messageDiv.css('left', '-60px');
              messageDiv.css('padding', '5px 30px 8px');
              messageDiv.css('vertical-align', 'middle');
              messageDiv.css('border', '3px solid ' + borderColor);
			  messageDiv.css('border-top', '0px');
              messageDiv.css('font-size', '13px');
              messageDiv.css('font-family', 'Arial, Helvetica, Sans-Serif');
              messageDiv.css('z-index', '9999');
              //messageDiv.css('box-shadow', '0px 0px 5px #000');
			  messageDiv.css('width', '1006px');

              messagePara.css('margin', '0px');
              messagePara.css('padding', '0px');
              messagePara.css('line-height', '16px');
              messagePara.css('font-size', '1.0em');
              messagePara.css('text-align', 'center');

              responseForm.css('position', 'absolute');
              responseForm.css('top', '57px');
              responseForm.css('left', '30px');
              responseForm.css('width', '100px');

              /*yesButton.css('margin-right', '10px');
              yesButton.css('background', '#fff');
			  yesButton.css('border', '1px solid #000');
			  yesButton.css('font-size', '1.0em');
			  yesButton.css('width', '40px');
			  yesButton.css('font-weight', 'bold');

              noButton.css('background', '#fff');
			  noButton.css('border', '1px solid #000');
			  noButton.css('font-size', '1.0em');
			  noButton.css('width', '40px');
			  noButton.css('font-weight', 'bold');*/

              moreInfoDiv.css('background-color', backgroundColor);
              moreInfoDiv.css('color', textColor);
              moreInfoDiv.css('position', 'fixed');
              moreInfoDiv.css('left', '20px');
              moreInfoDiv.css('right', '20px');
              moreInfoDiv.css('padding', '7px 10px 7px 10px');
              moreInfoDiv.css('vertical-align', 'middle');
              moreInfoDiv.css('border', '1px solid ' + borderColor);
              moreInfoDiv.css('border-top', 'none');
              moreInfoDiv.css('font-size', '12px');
              moreInfoDiv.css('font-family', 'Arial, Helvetica, Sans-Serif');
              moreInfoDiv.css('z-index', '9998');
              moreInfoDiv.css('display', 'none');
              moreInfoDiv.css('border-radius', '0px 0px 10px 10px');
              moreInfoDiv.css('-moz-border-radius', '0px 0px 10px 10px');
              moreInfoDiv.css('box-shadow', '0px 0px 5px #000');

              messagePara.append(yesButton);
              messagePara.append('".');
              //responseForm.append(noButton);

              messageDiv.append(messagePara);
              messageDiv.append(responseForm);

              $('#wrapper').append(messageDiv);
              $('#wrapper').append(moreInfoDiv);

              var origHeight = messageDiv.height();

              messageDiv.css('display', 'none');
              messageDiv.fadeIn(400);

               yesButton.click( function ()
                {
                  //hideMoreInfo();
					  answer = true;
                      yesCallback();
					  yesPermanentCallback();
					  hideDiv();
                     // nextStep();
                });

        /*      noButton.click( function ()
                {
                  hideMoreInfo();
                      answer = false;
                      noCallback();
                      if (options.noConsentCallback != null) {
                        options.noConsentCallback();
                      }
					  yesPermanentCallback();
                      hideDiv();
                });

              function nextStep()
                {
                  messageDiv.fadeOut(200, function()
                    {
                      //messageDiv.css('display','none !important' );
                      //messagePara.html(options.permanentMessage + ' <a href="#">More Info</a>');
                      //moreInfoDiv.html(options.permanentMoreInfo);
                      //bindMoreInfo();
                      //messageDiv.fadeIn(200);
                    });
                  step++;
                }
*/
              function hideDiv()
                {
                  messageDiv.fadeOut(400, function()
                    {
                      messageDiv.remove()
                    });
		}
            }

          function cookiesHasConsent()
            {
              var cookieVal = readCookie(sessionCookieName);

              if (cookieVal === 'true')
                {
                  cookieVal = true;
                }
              else if (cookieVal === 'false')
                {
                  cookieVal = false;
                }
              return cookieVal;
            }

          function cookiesHasPermanentConsent()
            {
              var permanentCookieVal = readCookie(permanentCookieName);

              if (permanentCookieVal === 'true')
                {
                  permanentCookieVal = true;
                }
              else if (permanentCookieVal === 'false')
                {
                  permanentCookieVal = false;
                }
              return permanentCookieVal;
            }

          function cookiesClickedYes()
            {
              //createCookie(sessionCookieName, answer);
              insertGA();
            }

          function cookiesClickedNo()
            {
              createCookie(sessionCookieName, answer);
            }

          function cookiesClickedYesPermanent()
            {
              createCookie(permanentCookieName, answer, 365);
            }

          function cookiesClickedNoPermanent()
            {
            }

          function createCookie(name, value, days)
            {
              if (days)
                {
                  var date = new Date();

                  date.setTime(date.getTime()+(days*24*60*60*1000));
                  var expires = ";expires="+date.toGMTString();
		}
              else
                var expires = "";
              document.cookie = name+"="+value+expires+"; path=/";
            }

          function readCookie(name)
            {
              var nameEQ = name + "=";
              var ca = document.cookie.split(';');

              for (var i = 0; i < ca.length; i++)
                {
                  var c = ca[i];

                  while (c.charAt(0)==' ')
                    {
                      c = c.substring(1, c.length);
                    }
                  if (c.indexOf(nameEQ) == 0)
                    {
                      return c.substring(nameEQ.length, c.length);
                    }
                }
              return null;
            }

          function bindMoreInfo()
            {
              moreInfoDiv.find('p').css('margin', '0px');
              moreInfoDiv.find('p').css('padding', '0px');
              moreInfoDiv.find('p').css('line-height', '16px');
              moreInfoDiv.find('p').css('font-size', '1.0em');
              messagePara.find('a').click( function()
                {
                  if (moreInfoDiv.is(':visible'))
                    {
                      hideMoreInfo();
                    } 
                  else
                    {
                      showMoreInfo(); 
                    }
                });
            }

          function showMoreInfo()
            {
              moreInfoDiv.css('top', messageDiv.outerHeight());
              moreInfoDiv.fadeIn(400);            
              return false;
            }

          function hideMoreInfo()
            {
              moreInfoDiv.fadeOut(400);
              return false;
            }
	
          function addTracking()
            {
              $.pageTracker = _gat._getTracker(options.gaKey);
              $.pageTracker._initData();
              $.pageTracker._trackPageview();
            }

          function insertGA()
            {
              if (!gaInserted)
                {
                  try
                    {
                      var gaURL = (location.href.indexOf('https') == 0 ? 'https://ssl' : 'http://www');
                      gaURL += '.google-analytics.com/ga.js';

                      $.getScript(gaURL, function()
                        {
                          addTracking();
                        });
                    }
                  catch(err)
                    {
                      console.log('Failed to load Google Analytics:' + err);
                    }
                  gaInserted = true;	
                }
            }
        }
    }
})(jQuery);


