(function() {
	
	if (!jQuery.browser.msie) {
		return;
	}
	
	var startTimeKey = 'ally_svyst',
		cookie = jQuery.cookie,
		startTime = cookie(startTimeKey),
		pagesKey = 'ally_svypg',
		pages = cookie(pagesKey),
		pagesDelimiter = '|pg|',
		curPage = location.pathname,
		randomizer = Math.floor(Math.random() * 100),
	    isCustomer = (cookie('s_pers')||'').indexOf('s_uid') > -1,
		lastSurveyKey = 'ally_svy',
		takenSurveyLately = function () {
			return !!cookie(lastSurveyKey);
		},
		surveyURL = isFrench ? 'http://survey.ally.ca/wix/p825940415.aspx?&l=3084' : 'http://survey.ally.ca/wix/p825940415.aspx?&l=4105',
		browser = ALLY.browser,
		lightbox = ALLY.ui.lightbox,		
		_tryShow = function () {
			
			if (!browser.cookiesEnabled) {
				return;
			}
			
			var now = +new Date,
				beenOnSiteMoreThanTwoMins = now - startTime > 120000;
			if ( ( beenOnSiteMoreThanTwoMins && pages.length>1 ) &&
				 !cookie("ally_chatShown") && 
				 !ALLY.util.user.isLoggedIn() && 
				 !takenSurveyLately() &&
         		 !isCustomer &&
				  randomizer < 50
				) {
					
				ALLY.util.survey.show();
			}
			
		},
		_show = function () {
			
			window.open(surveyURL, "_blank", "resizable=yes,scrollbars=yes,height=400,width=700");
				
			cookie(lastSurveyKey, 1, {expires: 180, path: '/'});

			cookie('ally-survey-lastime', 1, {expires: 180, path: '/'});
			
			cookie(startTimeKey, null);
			cookie(pagesKey, null);
			
			if (typeof lpSendData != "undefined") {
				lpSendData('session','SurveyOffered','y');	
			}
			
		};
		
	if (!browser.cookiesEnabled || takenSurveyLately() ) {
		return;
	}

	if (!startTime) {
		startTime = +new Date;

		cookie(startTimeKey, startTime, { path: '/'});
	} 

	if (pages) {
		pages = pages.split(pagesDelimiter);

		var found, i = pages.length -1;

		for ( ; i > -1; i--) {
			if ( pages[i] == curPage ) {
				found = true;
				break;
			}
		}

		if (!found) {
			pages.push( curPage );
		}

	} else {

		pages = [ curPage ];

	}

	cookie(pagesKey, pages.join(pagesDelimiter), { path: '/'});

	jQuery( window ).bind('beforeunload', function (e) {
		if (e && e.clientY < 0 && (e.clientX > (document.documentElement.clientWidth - 5) || e.clientX < 15)) {
			_tryShow();	
		 }	
	});
	
	jQuery("body")
		.bind("load.ally-survey", function(event){
			$.cookie("ally-survey-lastpage", null);
		})
		
		.bind("click.ally-survey", function(event){
			var t = event.target;
			if(t.tagName.toLowerCase() === "a"){
				$.cookie("ally-survey-lastpage", t.href);
			}
		});
	
	
			
	return {
		tryShow: _tryShow,
		show: _show
	};
	
})();

