// *************************************************************************
// *                                                                       *
// * (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:                  '<img style="border: none; vertical-align: middle; margin-right: 5px; margin-top: -2px;" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAllJREFUeNq8k19IU2EYxp9v5+xsLjVtburm/JNOjqWsCP9UaCFiJYENAskuujC8iMAuuojhRREmRETdFF15XURJRCJR5MhFDWLZXJtzY/5brjW2rM1tZ+eczmYU0U0Q9t188H0Pv+d9n+/9iCiK+JdFNhsg/7FzfwWIJ1I6XyDU4/auHFxcChtja/Hi7HVRoSpWadB4WaN+qq6m7MkWlWL5NwDPi4zN7hm+N247M2WbVfsDYcTXRRA5kxOJXBp5SqC2WoP2vTuifcf23d7fyl6mKVmScByvuv/o1d2RGw+OOl2LQEZErbEc5pYE6tWhHMD/RYfHbwvgtM8DQgZ61gDLOfPkwMnO42TK5hoZsoxZHO98oBgGTQ0VuNgbgKnACiWdQbYFAQSu9QOYV5yWaqaQTKaxvboUVRWaa/SL6dl+qWcoVUqkMjROHSpAi9oKz2o+rkzUQy4TQcsEpLkoStkZFBZrc1V5fB/RyBr6aLmc5gghyIUpSsIMAZFciOT7K18RCoUCNrsP3rnXgGzj9NJwP0eNjo4w712L3X6JSFHAQoSBodIAdqsXJ5oX0GsKorsxirJqE6Z9anyOfZN8BLS1NeDswOGrRBBEavK549bozYeDtjceZBJpaCu06NoF1BRHck6BWAmeOoBPSyHQKgate4y4MGQe6+naPfhzDpwflgbGJ+znn1lnWLc3iHA0BV7cqJUiPEqKFGDrdOjsaJrrPdJ83bSz6s4fg8TzgnJlNdrhD4Tal4MRdu1rQp3VFObnRfQ6tVtK/qW+fJtVev/Ef/sLmw/4LsAAfXwC5XNN7E8AAAAASUVORK5CYII=" alt=" " /> The <a href="http://www.ico.gov.uk/for_organisations/privacy_and_electronic_communications/cookie_rules_prepare.aspx">rules about cookie use on websites</a> changed on 26 May 2011 and all UK websites now need to ask your permission to use cookies. Our site uses cookies and one of the cookies we use is essential for parts of the site to operate and has already been set. You may delete and block all cookies from this site, but parts of the site will not work. <strong>Do you consent to receiving all cookies from the GSS site?</strong>',
                       permanentMessage:         'Would you like us to save your preference permanently? We will remember this preference using a cookie on your machine.',
                       moreInfo:	         '<p>Under most circumstances you can visit the GSS website without telling us who you are and without revealing any personal information about yourself. On some occasions, however, we may need information from you.</p><p>We do collect standard internet log information and details of visitor behaviour patterns. We do this to find out things such as the number of visitors to the various parts of the site. We collect this information in a way which does not identify anyone.</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 = 'GSS_cookies';
          var permanentCookieName = 'GSS_cookies_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+RyeUl8C41GU2C3dm1G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Hy+EZSGIzpwXOmwOQyPUIYNVjeXQj/FhSrNklw+oYEeoaNBDwyqKJ3i7tubwKIxZHtmLOhsuYGVQPzwA+4nPa0NPrAPugDN7bpQhOvILQRA3WJ1xFZJoCl8hmV0Yqm07olCImX6QaWxAmwDTGRcxYx8PskDoExIrGr8BMV1PidmxM6URYcjfo7E4cKzVSu9daqT+YScTFxXl0GnSGlCNiuK0sx3T6ecwN5qGwSodBhx0CiR3BCWaEJFBvFNuPyBQ9muTtyNrLyfpjphap0Een63gak14HT98SLAgT4lCRAabuG8ivsMJ/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 id="cookieMessageDiv" />');
              var iconImg = $('<img src="' + icon + '" alt=" " />');
              <!--var messagePara = $('<p>' + options.message + ' <a href="#">More Info</a></p>');-->
			  var messagePara = $('<p>' + options.message + ' To find out more about why you are seeing this banner, information about cookies on this website and how to delete cookies, see our <a href="http://www.gss.co.uk/privacy.gss#cookies">privacy statement</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', '14px');
              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', '1.25em');
              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', 'relative');-->
              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);-->
			  $('#cookieMessageDiv').append(messageDiv);
			  
              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);
					  if (step == 1)
					  	{
							responseForm.append(noButton);
						}
                    });
                  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('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);
