/*
Javascript based popup prompt for websurvey
Bespoke code below the ajax functions
*/


// PROPERTIES
var ENABLED = false;
var MAX_VIEWS = 2;
var MONTHS_TO_RUN = 3;
var DAYS_TO_RUN = MONTHS_TO_RUN * 31;
var SURVEY_ID = "RS7X0k_2bzl4rCfnAMtTH2fA_3d_3d";
var SURVEY_HEADING = 'Take part in the NGS Website survey';
var SURVEY_BODY = 'To ensure our website continues to serve the needs of our community, we would like to invite you to take part in a short online survey with an option to enter the prize draw. This will only take you a couple of minutes to complete.<br /><br /><br />';
var YES_TEXT = 'YES PLEASE - I am happy to take part in the short survey';
var NO_TEXT = 'No thanks - please return me to the website immediately';
	






var SURVEY_ROOT_PATH = 'http://www.surveymonkey.co.uk/s.aspx?sm=' + SURVEY_ID;
//var STYLING = 'display: block; float: left; position:absolute; top:350px; left:50%; margin:0; margin-left:-310px; width:400px; padding:10px 20px; background-color:#2B4858; border: solid 4px #F00; font-family: Arial, Helvetica, Sans-serif; color: #FFF;';
var LINK_STYLE = 'style="color: #2B4858; font-weight: bold;"';
var BUTTON_STYLING = "float: right; width: 22px; height: 22px; line-height: 22px; text-align: center; font-size: 13px; font-weight: bold;  text-decoration: none; color: #FFF;";
//var PATH_TO_IP = '/js/ipaddress.aspx';
//var IPS_TO_EXCLUDE = new Array();
//	IPS_TO_EXCLUDE[0] = "213.38.188.195"; //C
//	IPS_TO_EXCLUDE[1] = "195.59.25.130"; //E
//	IPS_TO_EXCLUDE[2] = "194.205.155.130"; //H


/*
 * Copyright 2006 SitePoint Pty. Ltd, www.sitepoint.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS;
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

function Ajax() {
  this.req = null;
  this.url = null;
  this.status = null;
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text'; // 'text', 'xml', 'object'
  this.mimeType = null;
  this.headers = [];


  this.init = function() {
    var i = 0;
    var reqTry = [
      function() { return new XMLHttpRequest(); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP') },
      function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];

    while (!this.req && (i < reqTry.length)) {
      try {
        this.req = reqTry[i++]();
      }
      catch(e) {}
    }
    return true;
  };
  this.doGet = function(url, hand, format) {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };
  this.doPost = function(url, dataPayload, hand, format) {
    this.url = url;
    this.dataPayload = dataPayload;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.method = 'POST';
    this.doReq();
  };
  this.doReq = function() {
    var self = null;
    var req = null;
    var headArr = [];

    if (!this.init()) {
      alert('Could not create XMLHttpRequest object.');
      return;
    }
    req = this.req;
    req.open(this.method, this.url, this.async);
    if (this.method == "POST") {
      this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    if (this.method == 'POST') {
      req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    self = this;
    req.onreadystatechange = function() {
      var resp = null;
      self.readyState = req.readyState;
      if (req.readyState == 4) {

        self.status = req.status;
        self.statusText = req.statusText;
        self.responseText = req.responseText;
        self.responseXML = req.responseXML;

        switch(self.responseFormat) {
          case 'text':
            resp = self.responseText;
            break;
          case 'xml':
            resp = self.responseXML;
            break;
          case 'object':
            resp = req;
            break;
        }

        if (self.status > 199 && self.status < 300) {
          if (!self.handleResp) {
            alert('No response handler defined ' +
              'for this XMLHttpRequest object.');
            return;
          }
          else {
            self.handleResp(resp);
          }
        }

        else {
          self.handleErr(resp);
        }
      }
    }
    req.send(this.dataPayload);
  };
  this.abort = function() {
    if (this.req) {
      this.req.onreadystatechange = function() { };
      this.req.abort();
      this.req = null;
    }
  };
  this.handleErr = function() {
    var errorWin;
    // Create new window and display error
    try {
      errorWin = window.open('', 'errorWin');
      errorWin.document.body.innerHTML = this.responseText;
    }
    // If pop-up gets blocked, inform user
    catch(e) {
      alert('An error occurred, but the error message cannot be' +
      ' displayed because of your browser\'s pop-up blocker.\n' +
      'Please allow pop-ups from this Web site.');
    }
  };
  this.setMimeType = function(mimeType) {
    this.mimeType = mimeType;
  };
  this.setHandlerResp = function(funcRef) {
    this.handleResp = funcRef;
  };
  this.setHandlerErr = function(funcRef) {
    this.handleErr = funcRef;
  };
  this.setHandlerBoth = function(funcRef) {
    this.handleResp = funcRef;
    this.handleErr = funcRef;
  };
  this.setRequestHeader = function(headerName, headerValue) {
    this.headers.push(headerName + ': ' + headerValue);
  };

}

/*
 * Copyright 2008 Flipside Digital, www.flipsidedigital.net
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS;
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/

// COOKIE FUNCTIONS
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 + "_" + SURVEY_ID + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "_" + SURVEY_ID +"=";
	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 eraseCookie(name) {
	createCookie(name + "_" + SURVEY_ID,"",-1);
}



// SYSTEM FUNCTIONS
function setSeenToMax ()
{
	seen_count = readCookie("seen");	
	if (seen_count != null)
	{
		createCookie("seen", MAX_VIEWS, DAYS_TO_RUN);
	}
}

function incrementSeen ()
{
	seen_count = readCookie("seen");	
	if (seen_count != null)
	{
		seen_count++;
		createCookie("seen", seen_count, DAYS_TO_RUN);
	}	
}

function answerYes ()
{
	setSeenToMax ();
	hidePrompt();

	//window.location = SURVEY_ROOT_PATH;	
	window.open(SURVEY_ROOT_PATH, 'survey', 'location=yes,toolbar=yes,menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=600,width=800', false);
	
}

function answerNo ()
{
	incrementSeen();
	hidePrompt();
	createCookie("dont_show_yet", 'exists', 1);
}

function answerRemindMeLater ()
{
	hidePrompt();
	createCookie("dont_show_yet", 'exists', 7);
}

function showPrompt() 
{
    
    var promptDivOverlay = document.createElement('div');
    promptDivOverlay.setAttribute('id', 'SurveyOverlay');
    document.body.appendChild(promptDivOverlay);   

	var promptDiv = document.createElement('div');
	// create div
	promptDiv.setAttribute('id', 'SurveyPrompt');	

	// create headin
	var heading = document.createElement('h3');
	heading.innerHTML = SURVEY_HEADING; 
	
	var para1 = document.createElement('p');
	para1.innerHTML = SURVEY_BODY;
	
	var para2 = document.createElement('p');
	para2.innerHTML = '<a href="javascript:answerYes()" style="'+BUTTON_STYLING+'"><img src="/js/yes.gif" alt="yes" border="0"></a><a href="javascript:answerYes()" '+LINK_STYLE+'>' + YES_TEXT + '</a> <br /><br /> <a href="javascript:answerNo()" style="'+BUTTON_STYLING+'"><img src="/js/no.gif" alt="no" border="0"></a> <a href="javascript:answerNo()" '+LINK_STYLE+'>' + NO_TEXT + '</a>';
	
	// add links to div
	promptDiv.appendChild(heading);
	promptDiv.appendChild(para1);
	promptDiv.appendChild(para2);
	
	// add div to body
	document.body.appendChild(promptDiv);
	
}

function hidePrompt() 
{

    var promptDivOverlay = document.getElementById('SurveyOverlay');
    if (promptDivOverlay != null) {
        promptDivOverlay.style.display = "none";
    }


	var promptDiv = document.getElementById('SurveyPrompt');
	if (promptDiv != null)
	{
		promptDiv.style.display="none";
	}
}

function showAfterTomorrow ()
{
	createCookie("dont_show_yet", 'exists', 1);
}

// RUN PROMPT
function runPrompt () {
    if (!ENABLED) return;

	// vars
	var seen_count = 0;
	var dont_show_yet = '';
	var users_ip = '';
	var ajax = new Ajax();
	var exclude_ip = false;
	
	// ajax function
	// this is called below the definition
	//var handleAjax = function(str) {
	    // IP exclusion	
	    //users_ip = str;
	    //alert("users ip: " + users_ip);

	    //for (x in IPS_TO_EXCLUDE) {
	    //    if (IPS_TO_EXCLUDE[x] == users_ip) {
	    //        exclude_ip = true;
	    //    }
	    //}

	    //alert("exclude ip = " + exclude_ip);

	    //if (!exclude_ip) {
	        // Does the cookie exist?
	        seen_count = readCookie("seen");
	        dont_show_yet = readCookie("dont_show_yet");

	        //alert("seen_count: " + seen_count + " dont_show_yet: " + dont_show_yet);

	        if (seen_count == null) {
	            // try to create the cookie
	            createCookie("seen", 0, DAYS_TO_RUN);
	            showAfterTomorrow();
	            //alert("first visit - don't show popup");
	            //showPrompt();
	        }
	        else {

	            if ((seen_count >= 0) && (seen_count < MAX_VIEWS)) {
	                if (dont_show_yet == null) {
	                    showPrompt();
	                }
	            }
	        }
	    //}
	//}
	// IP exclusion	
	//ajax.doGet(PATH_TO_IP, handleAjax);			
}

