﻿// *************************************************************************
// *                                                                       *
// * (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:          '#ffffe1',
                       permanentBackgroundColor: '#bbffbb',
                       borderColor:              '#444',
                       textColor:                '#444',
                       message:                  '<a href="http://www.wolf-software.com" target=_blank><img style="border: none; vertical-align: middle; margin-right: 5px; margin-top: -2px;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEgAACxIB0t1+/AAAAAd0SU1FB9sFFBMiBWoOpnIAAAF3SURBVDjLrVIxS5xBFJw385YYD5FrrCyUELEQTCSSwkQ4sbGJXf6BqIWVv8JfoGVaIf4AGysDgjYBuxQhYm3lVZ77bPZk7/MOLPJg2d3Z92bn7Q4wJEhOk/xWQVMk94bmNoGUEnLO9wD+9DFJcwCu8NqQ9EtSkFw3swl3z+4eJD+MVGBmNf6ZJMxs18wWAfQPV0YSRARIrpVtF0AAyAD+VpdcmNmqmaWBC8umLemU5CeSm5LOSb4vj7pFchOASbol+XNY3wcppZB0V+OtVqvO2XL3cPcAMNv8hZmipg3gbR/sdruo2hzrS5f00FTw3d1D0k2F7Ug6MrPlQv7O3R8lnWCEgeYBvCnrfXePlFIU4i+N3JEe2Jb0rxTnQpALyTGA8ZTSy7pSfJhSiuZw91wpuQMw1vTBY5kXyv8PhJWXM7Mws7akjeezRl8dkme1SSJiwKkRgV6vNwHg/gVBSeyQ/BoR1znn34V4ycw+ApiMiB8550v8r3gCZahfg3Sdbr4AAAAASUVORK5CYII=" alt=" " /></a>Our primary school website would like to use cookies to store information on your computer to help us improve our website. A cookie is a little piece of text saved onto your computer and does NOT harm your computer. The cookies from Google Analytics we would like to store contain no information to allow us to identify you personally. Do you consent this website saving Google Analytics cookies on your computer?',
                       permanentMessage:         'Can we save your answer to the last question by storing a cookie on your computer? That way we will not ask you questions about Google Analytics cookies again',
                       moreInfo:	         	 '<a href="http://www.britannicaschool.hu/privacy.htm" target=_blank>To view the privacy policy of Britannica International School please click here</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>.',
                       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 affect your ability to use the website.</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+n0fAAAAAElFT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qGwSodBhx0CiR3BCWaEJFBvFNuPyBQ9muTtyNrLyfpjphap0Een63gak14HT98SLAgT4lCRAabuG8ivsMJ/Vz98oh0Ii+uCWNaHyvJiDSWe95cbNW0kQ61RPyw424zwRD4CWWJsTNJiHcuEUEq4L88CqdRAiYv0Hh7Eyn8WVEl+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('top', '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-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(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);
            }

          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);


