/**
* Pop-in distribution modal window for Survey-xact.
*/

/**
 * POPUP WINDOW CODE v1.3
 * Used for displaying DHTML only popups instead of using buggy modal windows.
 *
 * By Seth Banks (webmaster at subimage dot com)
 * http://www.subimage.com/
 *
 * Contributions by:
 * 	Eric Angel - tab index code
 * 	Scott - hiding/showing selects for IE users
 *	Todd Huss - inserting modal dynamically and anchor classes
 *
 * Up to date code can be found at http://www.subimage.com/dhtml/subModal
 *
 *
 * This code is free for you to use anywhere, just keep this comment block.
 */

var xact_gPopupMask = null;
var xact_gPopupContainer = null;
var xact_gPopFrame = null;
var xact_gSurveyURL = null;
var xact_gIntroURL = null;
var xact_gPopupIsShown = false;

var xact_gHideSelects = false;

var xact_gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var xact_gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = xact_keyDownHandler;
}

var xact_surveyKey;

var localized = new Array();
localized["da"] = new Array();
localized["da"]["yes"] = "Ja";
localized["da"]["no"] = "Nej";
localized["da"]["later"] = "Ja, men senere";
localized["en"] = new Array();
localized["en"]["yes"] = "Yes";
localized["en"]["no"] = "No";
localized["en"]["later"] = "Yes, but later";
localized["de"] = new Array();
localized["de"]["yes"] = "Ja";
localized["de"]["no"] = "Nein";
localized["de"]["later"] = "Ja aber später";

// Contains an interval of dates we check for
// Content (if any) is added by calling xact_dateInterval()
var dateIntervalFrom = new Array();
var dateIntervalTo = new Array();

/**
 * Initializes pop-in.
 */
function xact_initPopIn(language, baseURL, surveyKey) {

   if (language == undefined) {
      language = xact_getBrowserLanguage();
   }
   var lStrings = xact_getLocalizations(language);

   if (window.xact_introPageURL) {
      xact_gIntroURL = window.xact_introPageURL;
   } else {
      xact_gIntroURL = baseURL + "/PopinIntroduction?key=" + surveyKey + "&lang=" + language;
   }

   // Add the HTML to the body
   theBody = document.getElementsByTagName('BODY')[0];
   popmask = document.createElement('div');
   popmask.id = 'xact_popupMask';
   popcont = document.createElement('div');
   popcont.id = 'xact_popupContainer';
   popcont.innerHTML = '<div id="xact_popupInner">' +
                       '<iframe src="#" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="xact_popupFrame" name="xact_popupFrame" width="100%" height="100%"></iframe>' +
                       '<div id="xact_popinButtons">' +
                       '<button id="xact_popInYes" onclick="xact_hidePopIn(true, true)">' + lStrings["yes"] + '</button>' +
   //'<button id="popInLater" onclick="xact_hidePopIn(false, false)">' + laterButtonText + '</button>'+
                       '<button id="xact_popInNo" onclick="xact_hidePopIn(false, true)">' + lStrings["no"] + '</button>' +
                       '</div>' +
                       '</div>';
   theBody.appendChild(popmask);
   theBody.appendChild(popcont);

   xact_gPopupMask = document.getElementById("xact_popupMask");
   xact_gPopupContainer = document.getElementById("xact_popupContainer");
   xact_gPopFrame = document.getElementById("xact_popupFrame");

   // check to see if this is IE version 6 or lower. hide select boxes if so
   // maybe they'll fix this in version 7?
   var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
   if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
      xact_gHideSelects = true;
   }
   //   window.alert(xact_gHideSelects);
};

function xact_getLocalizations(language) {
   if (localized[language]) {
      return localized[language];
   } else {
      return localized["en"];
   }
};

/**
 * Gets the language of the browser
 */
function xact_getBrowserLanguage() {
   var browser_language = navigator.language;
   browser_language = (browser_language == undefined ? window.navigator.browserLanguage : browser_language);
   browser_language = (browser_language == undefined ? navigator.userLanguage : browser_language);

   if(browser_language) {
      browser_language=browser_language.substring(0,2);
   } else{
      browser_language="en";
   }
   return browser_language;
};

 /**
  * Shows the pop-in.
  *
  * @argument width - int in pixels
  * @argument height - int in pixels
  * @argument url - url to page, which is displayed in the popin window
  * @argument surveyURL - url to the survey
  * @argument surveyKey - key of the survey
  * @argument probability - (number between 0 and 1) the probability that the pop-in is shown.
  */

function xact_showPopIn(url, width, height, surveyURL, surveyKey, probability) {
   var random = Math.random();
   if (random > probability) {
      SurveyXactSetCookie(xact_surveyKey,1,surveyXactExpiry);
      return;
    }
   xact_surveyKey = surveyKey;
   xact_gSurveyURL = surveyURL;
	xact_gPopFrame.src = url;

   if(showPopinForSurvey(surveyKey)) {
      xact_gPopupIsShown = true;
      xact_disableTabIndexes();
      xact_gPopupMask.style.display = "block";
      xact_gPopupContainer.style.display = "block";

      // need to set the width of the iframe to the title bar width because of the dropshadow
      // some oddness was occuring and causing the frame to poke outside the border in IE6
      xact_gPopFrame.style.width = (width) + "px";
      xact_gPopFrame.style.height = (height) + "px";

      // calculate where to place the window on screen
      xact_centerPopWin(width, height);

      xact_setMaskSize();

      // for IE
      if (xact_gHideSelects == true) {
         xact_hideSelectBoxes();
      }
   }
};


var gi = 0;
var xact_doCenterPopIn = true;

function xact_IntervalCenterPopWin() {
   if(xact_doCenterPopIn == true) {
      xact_doCenterPopIn = false;
      window.setTimeout("xact_doCenterPopIn = true;xact_centerPopWin()",100);
   }
};

/**
 * Centers the pop-in window.
 */
function xact_centerPopWin(width, height) {

   if (xact_gPopupIsShown == true) {

      if (width == null || isNaN(width)) {
			width = xact_gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = xact_gPopupContainer.offsetHeight;
		}

		//var theBody = document.documentElement;
		var theBody = document.getElementsByTagName("BODY")[0];
		//theBody.style.overflow = "hidden";

		var scTop = 0; //parseInt(theBody.scrollTop,10);
		var scLeft = 0; //parseInt(theBody.scrollLeft,10);

		xact_gPopupMask.style.top = scTop + "px";
		xact_gPopupMask.style.left = scLeft + "px";
		xact_gPopupMask.style.top = "0px";
		xact_gPopupMask.style.left = "0px";
		xact_setMaskSize();

		//window.status = xact_gPopupMask.style.top + " " + xact_gPopupMask.style.left + " " + gi++;

      var scrollXY = xact_getScrollXY();
      var scrollX = parseInt(scrollXY[1],10);
      var scrollY = parseInt(scrollXY[0],10);

      var fullHeight = xact_getViewportHeight();
		var fullWidth = xact_getViewportWidth();

//      var windowHeight = xact_getWindowHeight();
//      var fullHeight = parseInt(windowHeight[1],10);
//		var fullWidth = parseInt(windowHeight[0],10);


      xact_gPopupContainer.style.top = (scrollX + (scTop + ((fullHeight - height) / 2))) + "px";
		xact_gPopupContainer.style.left =  (scrollY + (scLeft + ((fullWidth - width) / 2))) + "px";

//      xact_gPopupContainer.style.top = scrollX + "px";
//		xact_gPopupContainer.style.left =  scrollY + "px";

   }
};

xact_addEvent(window, "resize", xact_centerPopWin);
xact_addEvent(window, "DOMMouseScroll", xact_IntervalCenterPopWin);
window.onscroll = xact_IntervalCenterPopWin;

function xact_setMaskSize() {
	var theBody = document.getElementsByTagName("BODY")[0];

   var fullHeight = xact_getWindowHeight();
	var fullWidth = xact_getViewportWidth();

   // Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {
		popHeight = fullHeight;
	} else {
		popHeight = theBody.scrollHeight;
	}

   if(fullWidth > theBody.scrollWidth) {
      popWidth = fullWidth;
   } else {
      popWidth = theBody.scrollWidth;
   }

   xact_gPopupMask.style.height = popHeight + "px";
	xact_gPopupMask.style.width = popWidth + "px";
};
/**
 * Hides the pop-in window.
 *
 * @param showSurvey Tells if the survey should be shown.
 *      <code>true</code> if a new window should be opened showing the survey, <code>false</code> otherwise.
 * @param doNotShowPopInAgain Tells if the pop-in should be shown again
 *     <code>true</code> a cookie is set saying that the pop-in for the survey is not shown again; <code>false</code> otherwise.
 */
function xact_hidePopIn(showSurvey, doNotShowPopInAgain) {
   if(doNotShowPopInAgain == true) {
      SurveyXactSetCookie(xact_surveyKey,1,surveyXactExpiry);
   }
   xact_gPopupIsShown = false;
	var theBody = document.getElementsByTagName("BODY")[0];
	theBody.style.overflow = "";
	xact_restoreTabIndexes();
   if(showSurvey == true) {
      if(xact_gSurveyURL != null) {
         window.open(xact_gSurveyURL);
      }
   }
   if (xact_gPopupMask == null) {
		return;
	}
	xact_gPopupMask.style.display = "none";
	xact_gPopupContainer.style.display = "none";
	// display all select boxes
	if (xact_gHideSelects == true) {
		xact_displaySelectBoxes();
	}
};


// Tab key trap. iff popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function xact_keyDownHandler(e) {
    if (xact_gPopupIsShown && e.keyCode == 9) {
       return false;
    }
};

// For IE.  Go through predefined tags and disable tabbing into them.
function xact_disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < xact_gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(xact_gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				xact_gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
};

// For IE. Restore tab-indexes.
function xact_restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < xact_gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(xact_gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = xact_gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
};

/**
* Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*
* Thanks for the code Scott!
*/
function xact_hideSelectBoxes() {
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if(document.forms[i].elements[e].tagName == "SELECT") {
				document.forms[i].elements[e].style.visibility="hidden";
			}
		}
	}
};

/**
* Makes all drop down form select boxes on the screen visible so they do not reappear after the dialog is closed.
* IE has a problem with wanted select form tags to always be the topmost z-index or layer
*/
function xact_displaySelectBoxes() {
	for(var i = 0; i < document.forms.length; i++) {
		for(var e = 0; e < document.forms[i].length; e++){
			if(document.forms[i].elements[e].tagName == "SELECT") {
			document.forms[i].elements[e].style.visibility="visible";
			}
		}
	}
};

/**
 * X-browser event handler attachment and detachment
 * TH: Switched first true to false per http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html
 *
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function xact_addEvent(obj, evType, fn) {
   if (obj.addEventListener) {
      obj.addEventListener(evType, fn, false);
      return true;
   } else if (obj.attachEvent) {
      var r = obj.attachEvent("on" + evType, fn);
      return r;
   } else {
      return false;
   }
};
function xact_removeEvent(obj, evType, fn, useCapture) {
   if (obj.removeEventListener) {
      obj.removeEventListener(evType, fn, useCapture);
      return true;
   } else if (obj.detachEvent) {
      var r = obj.detachEvent("on" + evType, fn);
      return r;
   } else {
      alert("Handler could not be removed");
   }
};

function xact_getScrollXY() {
   var scrOfX = 0, scrOfY = 0;
   if (document.body && ( document.body.scrollLeft || document.body.scrollTop )) {
      //DOM compliant
      scrOfY = document.body.scrollTop;
      scrOfX = document.body.scrollLeft;
   } else  if (typeof( window.pageYOffset ) == 'number') {
      //Netscape compliant
      scrOfY = window.pageYOffset;
      scrOfX = window.pageXOffset;
   } else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop )) {
      //IE6 standards compliant mode
      scrOfY = document.documentElement.scrollTop;
      scrOfX = document.documentElement.scrollLeft;
   }
   return [ scrOfX, scrOfY ];
};

function xact_getWindowHeight() {
   var myWidth = 0, myHeight = 0;
   if (typeof( window.innerWidth ) == 'number') {
      //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
   } else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
      //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
   } else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
      //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
   }
   if (typeof(document.body.parentNode.scrollHeight) == 'number') {
      if (document.body.parentNode.scrollHeight > myHeight) {
         myHeight = document.body.parentNode.scrollHeight;
      }
   }
   return myHeight;
};

/**
 * Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/
 *
 * Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
 *
 * Gets the full width/height because it's different for most browsers.
 */
function xact_getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight;
	return window.undefined;
};

function xact_getViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth;
	if (document.body) return document.body.clientWidth;
	return window.undefined;
};

/**
 * Checks that the pop-in for a given survey should be shown.
 *
 * @return <code>true</code> if the pop-in for the survey should be shown; <code>false</code> otherwise.
 */
function showPopinForSurvey(surveyKey) {
  var performSurvey = true;
  if (window.surveyXactCookieSupport) {
    if (SurveyXactGetCookie(surveyKey) == null) {
    } else {
      performSurvey = false;
    }
  } else {
    //alert("no cookie support");
  }
   return performSurvey;
};

function xact_loadPopIn() {
   if (xact_checkDateInterval(new Date())) {
      xact_initPopIn(window.xact_language, window.xact_baseURL, window.xact_surveyKey);
      xact_showPopIn(xact_gIntroURL, window.xact_width, window.xact_height, window.xact_surveyURL, window.xact_surveyKey, window.xact_probability);
   }
};

function xact_startPopIn() {
   xact_addEvent(window, "load", xact_loadPopIn);
};

/**
 * Make it possible to accept ISO8601 formatted dates (and even time) in the form of
 * "2007-03-27" - March 27th, 2007
 * "2007-02-01T14:35:00" - February 1st, 2007 14:35
 *
 * Taken from http://delete.me.uk/2005/03/iso8601.html (under AFL - Academic Free License)
 */
Date.prototype.setISO8601 = function (string) {
      var regexp = "([0-9]{4})(-([0-9]{1,2})(-([0-9]{1,2})" +
                   "(T([0-9]{1,2}):([0-9]{1,2})(:([0-9]{1,2})(\.([0-9]+))?)?" +
                   "(Z|(([-+])([0-9]{1,2}):([0-9]{1,2})))?)?)?)?";
      var d = string.match(new RegExp(regexp));

      var offset = 0;
      var date = new Date(d[1], 0, 1);

      if (d[3]) {
         date.setMonth(d[3] - 1);
      }
      if (d[5]) {
         date.setDate(d[5]);
      }
      if (d[7]) {
         date.setHours(d[7]);
      }
      if (d[8]) {
         date.setMinutes(d[8]);
      }
      if (d[10]) {
         date.setSeconds(d[10]);
      }
      if (d[12]) {
         date.setMilliseconds(Number("0." + d[12]) * 1000);
      }
      if (d[14]) {
         offset = (Number(d[16]) * 60) + Number(d[17]);
         offset *= ((d[15] == '-') ? 1 : -1);
      }

//      offset -= date.getTimezoneOffset();
      time = (Number(date) + (offset * 60 * 1000));
      this.setTime(Number(time));
   };

/**
 * Add a date interval, so the popin is only displayed when the current date is within the specified interval
 * fromSting and toString must be in ISO 8601 format - YYYY-MM-DD[Thh:mm:ss]
 * fromString is the date from (and including) when the popin is displayed
 * toString is the date up till (not including) when the popin is displayed
 *
 * All calls to this function MUST be completed before calling xact_startPopIn()
 */
function xact_dateInterval(fromString, toString) {
   var fromDate = new Date();
   fromDate.setISO8601(fromString);
   dateIntervalFrom[dateIntervalFrom.length] = fromDate;
   var toDate = new Date();
   toDate.setISO8601(toString);
   dateIntervalTo[dateIntervalTo.length] = toDate;
};

// Checks if the test date is between any listed intervals in the dateIntervalFrom Array
function xact_checkDateInterval(testDate) {
   var result = false;
   if (dateIntervalFrom.length > 0) {
      for (i = 0; i < dateIntervalFrom.length; i++) {
         if ((testDate >= dateIntervalFrom[i]) && testDate <= dateIntervalTo[i]) {
            result = true;
         }
      }
   } else if (dateIntervalFrom == 0) {
      result = true;
   }
   return result;
};
