/*
 * Create a popup. The variableName parameter should be the name of
 * the variable this instance is assigned to. This is required as
 * HTML is dynamically generated and needs to know the popup instance
 * variable name for reference in onclick events.
 */
function comClicktoolsRbswebPopup(variableName) {
  var private = {
    pageWidth : function() {
      return window.innerWidth != null? window.innerWidth: document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth:document.body != null? document.body.clientWidth:null;},
    pageHeight : function() {
      return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;},
    posLeft : function() {
      return typeof window.pageXOffset != 'undefined' ? window.pageXOffset:document.documentElement && document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft? document.body.scrollLeft:0;},
    posTop : function() {
      return typeof window.pageYOffset != 'undefined' ? window.pageYOffset:document.documentElement && document.documentElement.scrollTop? document.documentElement.scrollTop: document.body.scrollTop?document.body.scrollTop:0;},
    fn : function(x){
      return document.getElementById(x);},
    scrollFix : function(){
      var obol=private.fn('ol');obol.style.top=private.posTop()+'px';obol.style.left=private.posLeft()+'px'},
    sizeFix : function(){
      var obol=private.fn('ol');obol.style.height=private.pageHeight()+'px';obol.style.width=private.pageWidth()+'px';},
    kp : function(e){ky=e?e.which:event.keyCode;if(ky==88||ky==120)hm();return false},
    inf : function(h){
      tag=document.getElementsByTagName('select');
      for(i=tag.length-1;i>=0;i--)
        tag[i].style.visibility=h;
    /*  tag=document.getElementsByTagName('iframe');*/
    /*  for(i=tag.length-1;i>=0;i--)*/
    /*    tag[i].style.visibility=h;*/
      tag=document.getElementsByTagName('object');
      for(i=tag.length-1;i>=0;i--)tag[i].style.visibility=h;},
    sm : function(obl, wd, ht){
      var h='hidden';
      var b='block';
      var p='px';
      var obol=private.fn('ol');
      var obbxd = private.fn('mbd');
      obbxd.innerHTML = private.fn(obl).innerHTML;obol.style.height=private.pageHeight()+p;obol.style.width=private.pageWidth()+p;obol.style.top=private.posTop()+p;obol.style.left=private.posLeft()+p;obol.style.display=b;var tp=private.posTop()+((private.pageHeight()-ht)/2)-12;var lt=private.posLeft()+((private.pageWidth()-wd)/2)-12;var obbx=private.fn('mbox');obbx.style.top=(tp<0?0:tp)+p;obbx.style.left=(lt<0?0:lt)+p;obbx.style.height=ht+p;private.inf(h);obbx.style.display=b;return false;},

    initmb : function(){
      var ab='absolute';
      var n='none';
      var obody=document.getElementsByTagName('body')[0];
      var frag=document.createDocumentFragment();
      var obol=document.createElement('div');
      obol.setAttribute('id','ol');
      obol.style.display=n;
      obol.style.position=ab;
      obol.style.top=0;
      obol.style.left=0;
      obol.style.zIndex=998;
      obol.style.width='100%';
      frag.appendChild(obol);
      var obbx=document.createElement('div');
      obbx.setAttribute('id','mbox');
      obbx.style.display=n;
      obbx.style.position=ab;
      obbx.style.zIndex=999;
      var obl=document.createElement('span');
      obbx.appendChild(obl);
      var obbxd=document.createElement('div');
      obbxd.setAttribute('id','mbd');
      obl.appendChild(obbxd);
      frag.insertBefore(obbx,obol.nextSibling);
      obody.insertBefore(frag,obody.firstChild);
      window.onscroll = private.scrollFix; window.onresize = private.sizeFix;
    },

    /* clicktools */
    var_SURVEY_ID : 'b41194380ffb6c0',
    var_POPUP_URL : '',
    // NO_POPUP_DAYS defines the time a user will not be prompted again for
    // after either completing a survey or clicking the 'No, and don't ask again' button
    var_NO_POPUP_DAYS : 120,
    var_SAMPLE_PER_THOUSAND : 100,
    var_DDA_DELAY_SECS : 5,
    var_TITLE : "Customer Satisfaction Survey",
    var_MESSAGE : "We value your feedback. Would you like to participate in a short survey regarding your experience with this site today?",
	var_DOMAIN : "feedback.natwest.com",

    surveyed : function(surveyid) {
      return (private.getcookie('surveyed') == 'true') ? true : false;
    },

    addPopupContent : function() {
      var body = document.getElementsByTagName('body')[0];
      var container = document.createElement('div');
      container.setAttribute('id','surveybox');
      container.setAttribute('class','dialog');
      container.setAttribute('className','dialog'); // for IE
      body.appendChild(container);
      container.innerHTML =
      '<div id="surveypopup" class="ct_nw">\
       <div id="popupheader" style="background:url(\'/images/survey/'+(private.var_BRAND)+'popupheader.jpg\')"></div>\
       <div id="popupbody" style="font-family:Verdana,Arial,sans-serif;font-size:12px;">\
       <h3>'+private.var_TITLE+'</h3>\
       <p>'+private.var_MESSAGE+'<br/>\
       <div id="surveybuttons" style="text-align:center;align:center;"><a href="#" title="Yes" onclick="'+variableName+'.hm(\'surveybox\');'+variableName+'.okSelected();"><img src="/images/survey/'+(private.var_BRAND)+'surveyyes.gif"/ alt="yes" title="yes"></a>\
       <a href="#" title="Later" onclick="'+variableName+'.hm(\'surveybox\');'+variableName+'.laterSelected();"><img src="/images/survey/'+(private.var_BRAND)+'surveylater.gif" alt="Not now" title="Not now"/></a></div>\
       </div><div id="popupfooter" style="background:url(\'/images/survey/'+(private.var_BRAND)+'popupfooter.jpg\');"><a href="#" title="No, and don\'t ask again" onclick="'+variableName+'.hm(\'surveybox\');'+variableName+'.noSelected();"><img src="/images/survey/'+(private.var_BRAND)+'no.jpg" alt="No, and don\'t ask again" title="No, and don\'t ask again"/></a>\
      </div></div>';
    },

    cookiesEnabled : function() {
      private.setcookie('cookietest','true');
      return (private.getcookie('cookietest') != 'true') ? false : true;
    },

    getcookieval : function(offset) {
      var endstr = document.cookie.indexOf (";", offset);
      if (endstr == -1) {
        endstr = document.cookie.length;
      }
      return unescape(document.cookie.substring(offset, endstr));
    },

    getcookie : function(name) {
      var arg = name + "=";
      var alen = arg.length;
      var clen = document.cookie.length;
      var i = 0;
      while (i < clen) {
        var j = i + alen;
        if(document.cookie.substring(i, j) == arg)
          return private.getcookieval (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
      }
      return null;
    },

    setcookie : function(name, value) {
      var argv = private.setcookie.arguments;
      var argc = private.setcookie.arguments.length;
      var expires = (argc > 2) ? argv[2] : null;
      var path = (argc > 3) ? argv[3] : null;
      var domain = (argc > 4) ? argv[4] : null;
      var secure = (argc > 5) ? argv[5] : false;
      document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
    },

    sample : function() {
      s = Math.floor(Math.random()*1000)+1;
      return (s < private.var_SAMPLE_PER_THOUSAND);
    },

    survey : function() {
      if(private.sample()) {
				// Time Delay - if it doesn't equal zero, then follow the time delay
				if(private.var_DDA_DELAY_SECS > 0){
				setTimeout(variableName+'.popupwindow(400, 245)', private.var_DDA_DELAY_SECS*1000);
				}
				// Page Exit - if time delay is set to zero, then show on page exit (Only for normal links, not popups or bookmarks)	
				else  {	
				$("a:not([onclick],[href^='#'],[target])").click(			
					function() {
						private.redirectUrl = $(this).attr("href");
						eval(variableName+'.popupwindow(400, 245)');
						return false;
					}
				);
			}
		}
	},  

    addLoadEvent : function(func) {
		$(document).ready(func);
    },	
	
    init : function() {
      private.addLoadEvent(function(){
        if (document.createDocumentFragment) { // reject IE 5.5
          if (private.cookiesEnabled() && !private.surveyed(private.var_SURVEY_ID) && !(private.getcookie('surveylater') == 'true')) {
            private.var_POPUP_URL = "http://"+(private.var_DOMAIN)+"/survey?iv="+escape(private.var_SURVEY_ID);
            private.initmb();
            private.addPopupContent();
            private.survey();
          }
        }
      });
    }
  }; 

  comClicktoolsRbswebPopup.prototype.popupwindow = function(w, h){
    private.sm('surveybox',w,h);
    return false;
  };

  comClicktoolsRbswebPopup.prototype.hm = function(){
    var v='visible';
    var n='none';
    private.fn('ol').style.display=n;private.fn('mbox').style.display=n;private.inf(v);
    document.onkeypress='';
	if(private.redirectUrl) document.location.href = private.redirectUrl;
  };

  // Set the (Clicktools) Id of the survey that will be launched when user presses 'Yes' button
  comClicktoolsRbswebPopup.prototype.setSurveyId = function(surveyId) {
    private.var_SURVEY_ID = surveyId;
  };

  // Set the title displayed in the popup
  // Default value is "Customer Satisfaction Survey"
  comClicktoolsRbswebPopup.prototype.setTitle = function(title) {
    private.var_TITLE = title;
  };

  // Set the message displayed inside the popup
  // Default value is "We value your feedback. Would you like to participate in a short survey regarding your experience with this site today?",
  comClicktoolsRbswebPopup.prototype.setMessage = function(message) {
    private.var_MESSAGE = message;
  };

  // Set the delay in seconds before the popup is displayed (assuming it is triggered).
  // The delay allows the page the popup appears on to be fully rendered first.
  comClicktoolsRbswebPopup.prototype.setPopupDelay = function(delay) {
    private.var_DDA_DELAY_SECS = delay;
  };

  // Set how many times on average the popup will be displayed per 1000 page
  // hits, e.g. a value of 100 will trigger the popup approximately every 10th hit.
  // Default value is 100
  comClicktoolsRbswebPopup.prototype.setSampleRate = function(sampleRate) {
    private.var_SAMPLE_PER_THOUSAND = sampleRate;
  };

  // Called from onClick event when user clicks the 'Yes' button on the popup
  comClicktoolsRbswebPopup.prototype.okSelected = function() {
    var expdate = new Date();
    expdate.setTime(expdate.getTime()+(private.var_NO_POPUP_DAYS*24*60*60*1000));
    private.setcookie('surveyed','true',expdate);
    window.open(private.var_POPUP_URL,"survey","width=784,height=600,scrollbars=1");
  };

  // Called from onClick event when user clicks the 'No, and don't ask again' button on the popup
  comClicktoolsRbswebPopup.prototype.noSelected = function() {
    var expdate = new Date();
    expdate.setTime(expdate.getTime()+(private.var_NO_POPUP_DAYS*24*60*60*1000));
    private.setcookie('surveyed','true',expdate);
  };

  // Called from onClick event when user clicks the 'Not Now' button on the popup
  comClicktoolsRbswebPopup.prototype.laterSelected = function() {
    // stop user being asked again this session
    private.setcookie('surveylater','true');
  };
  
  // Domain Selector
  comClicktoolsRbswebPopup.prototype.setDomain = function(domain) {
    private.var_DOMAIN = domain;
  };
  
    // Domain Selector
  comClicktoolsRbswebPopup.prototype.setBrand = function(brand) {
    private.var_BRAND = brand;
  };

  private.init();
};

