//Custom survey launch for BAH

// Take advantage of jquery
jQuery(document).ready(function(){

    var survey = new ProvidyaWebInterceptSurvey();
    
    // This is the Nth visitor to invite. set to 1 if you want every visitor invited or 0
    // to bypass the cookie check completely for testing.
	// was set to 10, pushing it back to 20
    survey.NthVisitorToInvite = 20;
    
    // The survey to launch
    survey.SurveyUrl = '/media/file/survey_popup.html';
    
    // We want to send the current URL and referrer in the survey invite
    survey.AddUrlParameter('entryPage', document.location.href); //jQuery.url.attr("path")
    survey.AddUrlParameter('referrerUrl', document.referrer);
    
    // Domains the cookie is valid for. Defaults to the current domain
    // Examples: www.example.com
    //	     example.com  (all subdomains too)
    // empty means the current domain
    survey.CookieDomain = '';
    
    // How long should the cookie last?
    // 0 or '' - Default is a session cookie and expires when you close the browser.
    // 'today' - for the rest of the day
    // number - Otherwise specify the number of minutes (1440 in a day)
    // 43200 - the number of minutes in 30 days
    survey.CookieDuration = '43200';
    
    // Cookie name used for surveys
    survey.CookieName = "BAH_SURVEY_INVITE";
    
    // The survey invite can be displayed as a 'popup' or a 'layer'
	survey.InviteStyle = 'layer';
    
    // This kicks off the survey. It will load itself on window.onload
    survey.Load();
 });

function CloseProvidyaSurvey()
{
    jQuery.closeDOMWindow();   
}
    
//----------------------------------------------------------------------------------------------
// Nothing should need changing below this line
//
// This is common generic code to support survey
// invitations.
//
// ProvidyaWebInterceptSurvey 
//   - Class to condionally invite the user to take a survey
// Minimal example would be
// var survey = new ProvidyaWebInterceptSurvey();
// survey.SurveyUrl = "http://google.com";
// survey.Load();
//
// ProvidyaSurveyUtils 
//    - Utility class
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
// Class to conditionally prompt the user to take a survey and
// if they agree, launch the survey
function ProvidyaWebInterceptSurvey()
{
	// private utility class
	this.utils = new ProvidyaSurveyUtils();
	
	// The url to send to for the survey. Can also override GetSurveyUrl() method
	this.SurveyUrl = "";
	
	// This is the Nth visitor to invite. set to 1 if  you want every visitor invited
	this.NthVisitorToInvite = 1;

	// Domains the cookie is valid for. Defaults to the current domain
	// Examples: www.example.com
	//	     example.com  (all subdomains too)
	this.CookieDomain = "";
	
	// How long should the cookie last? 
	// 0 or '' - Default is a session cookie and expires when you close the browser.
	// 'today' - for the rest of the day
	// number - Otherwise specify the number of minutes (1440 in a day)
	this.CookieDuration = "";
	
	// Can override the cookie path
	this.CookiePath = "/";
	
	// Cookie name used for surveys
	this.CookieName = "PROVIDYA_SURVEY_INVITE";

    // Store additional parameters to send with the URLs
	this.URLParameters = new Array();
    
    // The survey invite can be displayed as a 'popup' or a 'layer'
	this.InviteStyle = 'popup';
	
	// Main entry point to put a handler on window.onload
	this.Load = function()
	{
		// chain our actual work to window.onload 
        var survey=this;
        this.utils.AddEvent(window, "load",  function() { survey.CheckForInvite(); });
	}
	                
	this.CheckForInvite = function()
	{
        var invite = this.utils.GetRandom(this.NthVisitorToInvite) == this.NthVisitorToInvite;
        var cookieSet = this.utils.isCookieSet(this.CookieName);
        
        // Always update the cookie to store the exit page
        var currentPage = jQuery.url.attr("path");
        this.utils.SetCookie(this.CookieName, currentPage, this.CookieDomain, this.CookieDuration, this.CookiePath);
        
        // Check to make sure cookies are being accepted
        if ( ! this.utils.isCookieSet(this.CookieName) )
        {
            // avoid asking
            cookieSet = true;   
        }
        
        if ( this.NthVisitorToInvite == 0 || !cookieSet )
        {
                // Prompt if they are the Nth visitor
                if ( this.NthVisitorToInvite == 0 || invite )
                {
                    this.Invite();
                }
        } 
	}
	
	this.Invite = function()
	{
        var url = this.utils.AddUrlParameters( this.SurveyUrl, this.URLParameters);
        if ( this.InviteStyle == 'popup' )
        {
            //half the screen width minus half the new window width (plus 5 pixel borders).
            var screenWidth = (window.screen.width/2) - (300 + 5);
            //half the screen height minus half the new window height (plus title and status bars).
            var screenHeight = (window.screen.height/2) - (315 + 50);

            var surveyWin=window.open(url,'SurveyWin','toolbar=no,menubar=no,location=no,resizable=yes,status=no,width=600,height=630,scrollbars=no');
            surveyWin.moveTo(screenWidth,screenHeight);
            surveyWin.focus();	
        }
        else // this.InviteStyle == 'layer'
        {
            jQuery.openDOMWindow({ 
                height:490, 
                width:545,
                windowSource:'iframe', 
                windowSourceURL:url,
                windowPadding:0,
                anchoredClassName:'ProvidyaSurvey',
                overlayOpacity:'65'//,
                //modal:1
                }); 
        }
	}

    // Call this method if you need some special logic to 
	// add arguments to the survey URL on the fly
	this.AddUrlParameter = function(name, val)
	{
		this.URLParameters[name] = val;
	}
}

//----------------------------------------------------------------------------------------------
// Utility stuff

function ProvidyaSurveyUtils()
{

    this.Trim = function (str) 
    {
        if ( str )
        {
            return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        }
        return '';
    }	
    
	/**
	 * X-browser event handler attachment and detachment
	 * @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
	 */
	this.AddEvent = function (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;
	 }
	}
	
	
	this.RemoveEvent = function (obj, evType, fn)
	{
	 if (obj.removeEventListener){
	    obj.removeEventListener(evType, fn, false);
	    return true;
	 } else if (obj.detachEvent){
	    var r = obj.detachEvent("on"+evType, fn);
	    return r;
	 } else {
	    return false;
	 }
	}
	
	

	// Sets a cookie showing the user has been prompted already
	//TODO: support varing expired dates and perhaps paths
	this.SetCookie = function(name, value, domain, duration, path)
	{
	        var cookie=name + "=" + escape(value) + ";";
	        if ( domain ) cookie += " domain=" + domain + ";";
	        if ( path ) cookie += " path=" + path + ";";
	        
	        var expire = this.GetCookieExpireDate(duration);
	        if (expire) cookie += " expires=" + expire.toGMTString() + ";";
	        
	        document.cookie=cookie;
	}
    
    this.isCookieSet = function(name) 
    {
        var value = this.Trim(this.GetCookie(name));
        return value && value.length > 0;
    }
	
	// Get a cookie
	this.GetCookie = function(name) 
	{
	   arg=name+"=";
	   alen=arg.length;
	   clen=document.cookie.length;
	   i=0;
	   while (i<clen) {
	      j=i+alen;
	      if (document.cookie.substring(i,j) == arg) 
	          {
	          return this.GetCookieValue(j);
	      }
	      i=document.cookie.indexOf(" ",i) + 1;
	      if (i === 0) {break;}
	   }
	}
	
	// get an actual cookie value from the jar
	this.GetCookieValue = function(offset)
	{
	   endstr=document.cookie.indexOf(";",offset);
	   if (endstr == -1) {endstr=document.cookie.length;}
	   return unescape(document.cookie.substring(offset,endstr));
	}
	
	// Returns a date object set for the expiration date of a cookie or false
	// How long should the cookie last? 
	// 0 or '' - Default is a session cookie and expires when you close the browser.
	// 'today' - for the rest of the day
	// number - Otherwise specify the number of minutes (1440 in a day (24*60))
	this.GetCookieExpireDate = function(duration)
	{
		if ( duration == '' || duration == 0 )
		{
			return '';	
		}
		
		if ( duration == 'today' )
		{
			var tomorrow = new Date();
		        tomorrow.setDate(tomorrow.getDate()+1);
		        tomorrow.setHours(0)
		        tomorrow.setMinutes(1);
		       	tomorrow.setSeconds(0);
		       	tomorrow.setMilliseconds(0);
		        return tomorrow;
		}
	        else
		{
		        var date = new Date();
		        date.setTime(date.getTime() + duration * 60 * 1000);
		        return date;
		}
	}
	
	this.DeleteCookie = function(cookie_name)
	{
	  var cookie_date = new Date();  // current date & time
	
	  cookie_date.setTime(cookie_date.getTime() - 1);
	  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
	}
	
	// Returns a random integer between 1 and max 
	// (which means max possible values)
	this.GetRandom = function(max)
	{
		if ( max == 1 )
		{
			return 1;
		}
		else
		{
	        	return (Math.floor(Math.random()*max)) + 1;
	        }
	}
	
	// Compare a regular expression to a cookie value
	this.CookieMatchesRegex = function(cookieName, regex)
	{
		var cookie = this.GetCookie(cookieName);
		if ( cookie)
		{
			return cookie.match(new RegExp(regex));
		}
		return false;
	}
    
    // Add a hash of parameters to a URL
	this.AddUrlParameters = function( baseUrl, parameters)
	{
		if ( parameters )
		{
			var out = baseUrl;
			if ( ! /\?/.test(out) )
			{
			   	out += "?";
			}
			var count = 0;
			for (var key in parameters)
			{
				out += (count++ > 0 ? "&" : "") + key + "=" + escape(parameters[key]);
			}
			return out;
		}
		else
		{
			return baseUrl;	
		}	
	}

}


