var showAfterTime = 60 * 1000;   // 60 seconds
var showAfterPages = 2;

var win2;

var surveyShownReset = 375 * 10 * 24;  // 10 years
var surveyWidth = 339; //547;
var surveyHeight = 387; //379;

var timeInterval; 
var scrollinterval;

var bShowSurvey = false;

var visitStart = 0;
var showDelayed = false;
var showNow = false;

/**
 * Opens the survey popup
 */
function openSurvey(){
	exitSurveyAnswer();
	win2=window.open('/p/survey.html','survey','top=5,left=5,height=500,width=660,scrollbars=yes,toolbars=yes,location=yes,resizable=yes,menubar=yes');
	if(win2!=null){
		win2.blur();
	}
}

/**
 * Enables and sets focus on the survey window
 */
function displaySurvey(){
	if(win2!=null){
		win2.enableMe();
		win2.focus();
	}
}

/**
 * Builds the survey html.  All styles and html are kept in the javascript
 * to minimize the required setup for moving this code between sites.  
 *
 * More complex popups should export the html and styles into the appropriate
 * places.
 *
 */
function buildSurvey(){

	var curtain = "<div id='surveyCurtain' style='opacity:.25;filter:alpha(opacity=25);background-color:#000000;display:none;position:absolute;left:0;top:0;z-index:500000;'></div>";
	var popupBg = "<div style='display:none;position:absolute;width:360px;z-index:500001;height:287px;border:0px solid; background-color:#ffffff' id='surveyBg'></div>";
	var popupShell = "<div style='display:none;position:absolute;width:360px;z-index:500002;height:287px; font-color:#606060; border-top:10px; border-top-style:solid; border-top-color:#F5822B;' id='surveyPopup'>";
			popupShell += "<div style='float:left; width:180px; padding-left:30px; margin-top:15px;'><img width='180' height='56' border='0' alt='Your Opinion Matters to Us' src='/p/images/yourOpinion.gif'/></div>";
			popupShell += "<div style='padding-right:13px; float:right; width:50px; text-align:right; font-color:#606060; margin-top:5px;'><a href='javascript:exitSurveyAnswer();' style='text-decoration:none; color:#bfbfbf;'> <img width='49' height='12' border='0' alt='Close' src='/p/images/closebox.gif' style='cursor: pointer;'/>  </a></div>";
			popupShell += "<div style='float:left; width:300px; padding-left:30px; margin-top:15px;'><p style='margin-top:0px; margin-bottom:6px;font-size:12px;color:#606060;line-height:18px;'>You have been randomly selected to participate in a brief survey that will help us enhance this Web site. ";
			popupShell += "Your answers will be used strictly to help us provide the right resources for you and your practice.</p><p style='margin-top:0px; margin-bottom:10px;font-size:12px;color:#606060; line-height:18px;'>The survey will appear in a separate window behind this browser window. Please complete the survey when you're finished visiting.</p></div>";
			popupShell += "<div style='float:left; width:147px; padding-left:28px; margin-top:3px;'><a href='javascript:openSurvey();' style='color:#a01b2c; text-decoration:none;'><img width='147' height='33' border='0' alt='Yes, I Will participate' src='/p/images/yesSurvey.gif'/></a></div>";
			popupShell += "<div style='float:left; width:147px; padding-left:13px; margin-top:3px;'><a href='javascript:exitSurveyAnswer();' style='color:#a01b2c; text-decoration:none;'><img width='147' height='33' border='0' alt='No, thanks' src='/p/images/noSurvey.gif'/></a></div>";
			popupShell += "</div>";
	document.write( curtain);
	document.write( popupBg );
	document.write( popupShell );
}


/**
 * Keeps the splash screen centered
 */
function scrollSurvey(){
  var popup = document.getElementById("surveyPopup");
  if(!popup || popup==undefined || popup.style.display != "block")return;
  
  var bg = document.getElementById("surveyBg");
  var iframe = document.getElementById("surveyiframe");
  var curtain = document.getElementById("surveyCurtain");
  var top =(getScrollY() + 20) ;


  // center
  var width;
  var height;
  
  
  // Window dimensions:
	//get the width
	if (window.innerWidth)
		width=window.innerWidth;
		else if (document.documentElement && document.documentElement.clientWidth)
		width=document.documentElement.clientWidth;
		else if (document.body)
		width=document.body.clientWidth;
		
	//get the height
	if (window.innerHeight)
		height=window.innerHeight;
		else if (document.documentElement && document.documentElement.clientHeight)
		height=document.documentElement.clientHeight;
		else if (document.body)
		height=document.body.clientHeight;
  
  
  var left = (width/2) - (surveyWidth/2);
  var topMod = (height/2) - (surveyHeight/2);
  
  popup.style.top = (topMod + top) + "px";
  popup.style.left = left + "px";
  
  bg.style.top = (topMod + top)+"px";
  bg.style.left = left + "px";
 
  curtain.style.width = width + "px";
  curtain.style.height = height + "px";
  curtain.style.top = (top-20) + "px";
  
  if(iframe){
    iframe.style.top = (topMod + top + 10) + "px";
    iframe.style.left = (left + 10) + "px";
  }
 
}

/**
 * Attempts to show the survey splash screen
 * Fails if the popup does not exist.
 */
function showSurvey(){
 
  var popup = document.getElementById("surveyPopup");

  // Check if the popup exists
  if(popup == null || popup==undefined){
    clearInterval(scrollinterval);
    clearInterval(timeInterval);
    return;
  }

  // record that the splash has been shown
  writeCookie("surv_surveyShown", "1", surveyShownReset);
 
  
  var bg = document.getElementById("surveyBg");
  var curtain = document.getElementById("surveyCurtain");
    
  popup.style.display = "block";
  bg.style.display = "block";
  curtain.style.display ="block";

  var iframe = document.getElementById("surveyiframe");
  if(iframe)
    iframe.style.display = "block";
  
  // wipe out the display interval
  clearInterval(timeInterval);
}

function hideSurvey(){
  var popup = document.getElementById("surveyPopup");
  if(!popup || popup==undefined)return;
  var bg = document.getElementById("surveyBg");
  var curtain = document.getElementById("surveyCurtain");
  
  popup.style.display = "none";
  bg.style.display = "none";
  curtain.style.display = "none";
  var iframe = document.getElementById("surveyiframe");
  if(iframe)
    iframe.style.display = "none";
  
  clearInterval(scrollinterval);
}

function exitSurveyAnswer(){
  writeCookie("surv_surveyShown", "1", surveyShownReset);

  hideSurvey();
}


/**
 * This function prepares the splash screen for display based on 
 * the rules
 */
function splash(){

    // set the page up to scroll the survey to make sure it stays centered
    scrollinterval = setInterval("scrollSurvey()", 22);  	    
    
    // if the survey request is delayed then turn on the interval to wait out the delay
    if(showDelayed){
        // 100 millisecond buffer to be on the safe side of slower loading browsers.  
        // this only matters if the time to show is less than 100 ms.
        if(showAfterTime < 100)showAfterTime = 100;
        
        // show the survey in the remaining number of milliseconds since the user first visited the site
        timeInterval = setInterval("showSurvey()", showAfterTime);
    }
    
    // otherwise if the survey should be shown immediatly then show it.
    else if(showNow){
        showSurvey();
    }
}

if(hasCookies()){


    // verify the user has cookies
    if(readCookie("surv_surveyShown") != "1"  ){
    
        // check if this is the first visit, if it is initialize the page count cookie
        var x = readCookie("surv_pagesVisited");
        if(isNaN(x)) x = 0;
        
        // increment the counter and save it
        x = Number(x) + 1;
        writeCookie("surv_pagesVisited", x);
        

        // build the html for the survey        
        buildSurvey();
        
        // if enough pages have been visited then show the popup immediatly
        if(x >= showAfterPages)
            showNow = true;
            
        // otherwise check the time tracker
        else{
        
            // get the time of hte first page load
            var t = readCookie("surv_time");
            var d = new Date();
            
            // if this is the firstt page load then initialize the cookie
            if(t == ""){
                visitStart = d.getTime();
                writeCookie("surv_time", visitStart);
            }
            else
                visitStart = Number(t);

            // get the remaining time before the survey should be displayed
            showAfterTime -= (d.getTime() - visitStart);
            
            // and prepare the time based display interval
            showDelayed = true;
        }
        
        addEvent(window, 'load', splash);
    } 
}






/**
 * Generic functions
 */
function hasCookies(){
  writeCookie("surv_cookieEnabled","1", null);	
  if(readCookie("surv_cookieEnabled") == "1"){
    deleteCookie("surv_cookieEnabled");
    return true; 
  }
  else 
    return false;
}


function getScrollY() {
  var scrOfY = 0;
  if(document.body && ( document.body.scrollTop ) ) {
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
  
}

function 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 writeCookie(name, value, hours)
{
  var expire = "";
  if(hours != null)
  {
    expire = new Date((new Date()).getTime() + (hours * 3600000));
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire +";path=/;";
}

function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}


function deleteCookie( name, path, domain ) {
  if ( readCookie( name ) ) document.cookie = name + "=" +
  ( ( path ) ? ";path=" + path : "") +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

