// *************************************************************************
// *                                                                       *
// * (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/>. *
// *                                                                       *
// *************************************************************************

/*
    Customised by Leigh Smith for use on ttsonline.net - 15/12/2011

     - Moved to bottom of the site so as not to interfere with site menu.
     - Changed the More Info message to better explain why this question is being asked
*/

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

      var defaults = {
                       gaKey:                    '',
                       backgroundColor:          '#ffffe1',
                       permanentBackgroundColor: '#bbffbb',
                       borderColor:              '#444',
                       textColor:                '#444',
                       message:                  'Do you consent to receiving Google Analytics cookies? Thomas Telford School use these to aid in improving and maintaining our website. We will remember this preference until you close your browser.',
                       permanentMessage:         'Would you like us to save your preference permanently? We will remember this preference using a cookie on your machine.',
                       moreInfo: '<p><b>PECR</b></p></br /><p>An amendment to the Privacy and Electronic Communications Act (PECR) is a change to legislation that comes into force in the UK on the 26th May 2011. This change requires websites to get consent from their vistors before setting cookies that are used to track usage on the website.</p><br /><p><b>Google Analytics</b></p><br /><p>This site uses Google Analytics, a web analytics service provided by Google, Inc. Google Analytics sets number of cookies (default is 4) in order to evaluate your use of the site and compile reports for us on activity on the site.</p><br /><p>Google stores the information collected by the cookie on servers in the United States. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google&apos;s behalf. Google will not associate your IP address with any other data held by Google.</p><br /><p>Google Inc are members of the US Safe Harbor Scheme. This scheme allows the transfer of data from within the EEA to countries that are outside of the EEA without having to enter into a specific data transfer agreement. Companies that sign up to the scheme are deemed to provide adequate protection for personal data transmitted from Europe. Google Inc’s registration is at <a href="http://safeharbor.export.gov/companyinfo.aspx?id=10543" target=_blank>http://safeharbor.export.gov/companyinfo.aspx?id=10543</a>.</p><br /><p>For more information on the cookies set by Google Analytics please go to: <a href="http://code.google.com/apis/analytics/docs/concepts/gaConceptsCookies.html" target=_blank>http://code.google.com/apis/analytics/docs/concepts/gaConceptsCookies.html</a>.</p><br /><p>Google has also created their own opt-out plugin which you can get from: <a href="http://tools.google.com/dlpage/gaoptout" target=_blank>http://tools.google.com/dlpage/gaoptout</a>.</p><br /><p>In addition to the cookies set by Google Analytics, this plugin will create a session based cookie (which will expire when you close your browser) containing a single "true" or "false" value, reflecting your choice.</p>',
                       permanentMoreInfo:        '<p><b>Permanent Preference</b></p><br /><p>In order for us to store your preference permanently we will need to set a cookie. This cookie will only contain a "true" or "false" value and nothing more. It is only used to store your preference for this site. Storing your preference permanently will simply stop you being asked this question each time you visit the site but will not effect your ability to use it.</p>',
                       noConsentCallback:        null
                    };

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

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

      cookieConsent();

      function cookieConsent()
        {
          var sessionCookieName = 'WS_pecr-ga_cookie';
          var permanentCookieName = 'WS_pecr-ga_cookie_perm';

          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 icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAABh0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjA1G8PgXAAAAmxJREFUOE+1kVtIk2EYxz+bVEwT8RQlSCO0ssT7rtLUufCmSwfGml1kWmDabrsSujCjibYD+ybT2efcN+cWOdcOanPNdJ4Hlh1ojm+Vp06278L897o7QUwveuEHD7w8v+d53z9F/a9D6+gEm93e2NLySExmJBx4jsHQKfV6tFssy6wWF18WHUigVquTrf22JW7pPEKzN6BsbTMSQeK+JWazuSk4fh+bv4/g10oG3C7rpkwmu7QvgVarPe3xOPj5yUK0Pq6ATlOKdzNSGLsZPxEc/afE5fJYPizcRnD0AurrG9BwV4bvi3mYHmPR2Hivek8BTdMl83PurQ3uDKZ8BZBKq3D9mgTfQrl47yuD1zscFolE6btK2tvbBT6fPxRZqMRGOB+TnnwUFZVCXlWEtWA2lkfTEPIr0dz88MGusTIMUzcX1G/9WDyF1ZlsBNgspKamofJqIaKDieCeC/C2NxNet+tnebnk3I4tSGwZTqdz5ePoWXz2J4EbScKMRYis4ydwp/oiODuFiIXCUu8hTPTdhEqlNu2IlWUtbWMv6hB9SZqHhOBcR8A5BHjadAwBnRARlkK4R4BP3YfxpiMJzmc9f+RyeUl8C41GU2C3dm1GRnIQHc5E1J1GVk7BLJOMnBwRFLViMj0FYVM6kWTEGesUQ99hmCDtQspisTqm3LVYm5aQzyrH2rgY66/LsB4ohUkpxiumAsvDEnwZuoKvhHjtFWOwTwWFQlFD6XR0oEOn4ml1K99Fq3iTUc/bzN28w2bmXQN9cQZI3W828j1ddKyTfhKjVcqYQU/Hampu6bZfkULIJeTtwfb9bpz8CymmbUgX+n0fAAAAAElFTkSuQmCC";
          var permanentIcon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD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iHcuEUEq4L88CqdRAiYv0Hh7Eyn8WVEl+7hK5lKwhRZIRsukqhBIzyKYeNIjaxoQXau5ncZN/uo/2v2r8M57MjqGVFhyOKTx5mHv0SObe+Fgmi5r0ppr7RPEPApH9JSxg5AoAAAAASUVORK5CYII=";

          var step = 0;
          var gaInserted = false;

          var answer = '';

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

          if (hasConsent == null)
            {
              var messageDiv = $('<div />');
              var iconImg = $('<img src="' + icon + '" alt=" " />');
              var messagePara = $('<p>' + options.message + ' <a href="#">More Info</a></p>');
              var responseForm = $('<div />');
              var yesButton = $('<input type="submit" name="yes" value="Yes" />');
              var noButton = $('<input type="submit" name="no" value="No" />');

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

              messageDiv.css('background-color', backgroundColor);
              messageDiv.css('color', textColor);
              messageDiv.css('position', 'fixed');
              messageDiv.css('bottom', '0px');
              messageDiv.css('left', '0px');
              messageDiv.css('right', '0px');
              messageDiv.css('padding', '7px 120px 7px 36px');
              messageDiv.css('vertical-align', 'middle');
              messageDiv.css('border-bottom', '1px solid ' + borderColor);
              messageDiv.css('font-size', '12px');
              messageDiv.css('font-family', 'Arial, Helvetica, Sans-Serif');
              messageDiv.css('z-index', '9999');
              messageDiv.css('box-shadow', '0px 0px 5px #000');

              iconImg.css('position', 'absolute');
              iconImg.css('top', '6px');
              iconImg.css('left', '10px');

              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', '4px');
              responseForm.css('right', '10px');
              responseForm.css('width', '100px');

              yesButton.css('margin-right', '10px');
              yesButton.css('font-size', '1.0em');

              noButton.css('font-size', '1.0em');

              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-bottom', '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', '10px 10px 0px 0px');
              moreInfoDiv.css('-moz-border-radius', '10px 10px 0px 0px');
              moreInfoDiv.css('box-shadow', '0px 0px 5px #000');

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

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

              $('body').append(messageDiv);
              $('body').append(moreInfoDiv);

              var origHeight = messageDiv.height();

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

              bindMoreInfo();

              yesButton.click( function()
                {
                  hideMoreInfo();
                  if (step == 0)
                    {
                      answer = true;
                      yesCallback();
                      nextStep();
                    }
                  else
                    {
                      yesPermanentCallback();
                      hideDiv();
                    }
                });

              noButton.click( function ()
                {
                  hideMoreInfo();
                  if (step == 0)
                    {
                      answer = false;
                      noCallback();
                      if (options.noConsentCallback != null) {
                        options.noConsentCallback();
                      }
                      nextStep();
                    }
                  else
                    {
                      noPermanentCallback();
                      hideDiv();
                    }
                });

              function nextStep()
                {
                  messageDiv.fadeOut(200, function()
                    {
                      messageDiv.css('background-color', permanentBackgroundColor);
                      messagePara.html(options.permanentMessage + ' <a href="#">More Info</a>');
                      iconImg.attr('src', permanentIcon);
                      moreInfoDiv.html(options.permanentMoreInfo);
                      bindMoreInfo();
                      messageDiv.fadeIn(200);
                    });
                  step++;
                }

              function hideDiv()
                {
                  messageDiv.fadeOut(400, function()
                    {
                      messageDiv.remove()
                    });
		}
            }
          else if (hasConsent == true)
            {
              insertGA();
            }

          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);
              insertGA();
            }

          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('bottom', 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);

