// Set Global Variables
var exit_popup;
var exit_frequency;

//Set Cookie
function setCookie(c_name,value,expiredays){
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
// Read Cookie
function getCookie(c_name){
	if (document.cookie.length>0){
  	c_start=document.cookie.indexOf(c_name + "=")
  	if (c_start!=-1){ 
    	c_start=c_start + c_name.length+1 
    	c_end=document.cookie.indexOf(";",c_start)
    	if (c_end==-1) c_end=document.cookie.length
    	return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
	return ""
}

//Open new window
function exit_popup_url(url,name){
	new_window = window.open(url, name, 'resizable,scrollbars,status,width=640,height=480,left=10,top=10')
}

//Returns a random whole number between 1-100
function displayFrequency(){
	var ranNum= Math.floor(Math.random()*101);
  return ranNum;
}

var surveyPages = 
[ {link: "/index.epx", survey: "home2"},
  {link: "/countries/index.epx", survey: "country2"},
  {link: "/solutions/index.epx", survey: "solutions2"},
  {link: "/industries/index.epx", survey: "industry2"},
  {link: "/lines-of-business/index.epx", survey: "LOB2"},
  {link: "/services-and-support/index.epx", survey: "services2"},
  {link: "/customer-testimonials/index.epx", survey: "ctest2"},
  {link: "/about-sap/index.epx", survey: "about2"},
  {link: "/our-partners/index.epx", survey: "partners2"},
  {link: "/events/index.epx", survey: "events2"},
  {link: "/news-reader/index.epx", survey: "news2"},
  {link: "/solutions/products/sap-bydesign/index.epx", survey: "design2"},
  {link: "/social/index.epx", survey: "social2"},
  {link: "/communities/index.epx", survey: "communities2"}
];

function getPageSurvey(path)
{
	for(var i=0; i<surveyPages.length; i++)
	{
		if(path.indexOf(surveyPages[i].link) == 0) // startsWith
			return surveyPages[i].survey;
	}
	return null;
}

//Check to see if cookie exists, if so do nothing, if not create cookie and display popup a percentage of the time determined by "frequency" variable
function callExitSurvey(){
	x=getCookie('exitSurvey');
	if (x!=null && x!=""){
		//cookie was found, don't fire popup
	}
	else{
		y = displayFrequency();
		if (y <= exit_frequency){
			setCookie('exitSurvey',true,14);
			exit_popup_url(exit_popup, "Survey");
		}
		else {
			//frequency conditions were not met, don't fire popup
		}
 	}
}

function checkExitSurvey(){
	var path = "";
	if (location.hash != null && location.hash.length > 1)
    {
	    path = referrer.substring(referrer.indexOf(location.host)+location.host.length);
	}
	else
	    path = location.pathname;
	var survey = getPageSurvey(path);
	if(survey != null)
	{
		exit_popup = "https://www.snapsurveys.com/swh/surveylogin.asp?k=130615916523&amp;s=" + survey + ".html";
		exit_frequency = 50;
		callExitSurvey();
	}
}
