/**
  * $Id$
  *
  * Project: DNI Site: Survey Component
  * Version: 0.0.1a
  * Author: ddicker
  *
 */
 
if (typeof(discovery) == "undefined") var discovery = {};
if (!discovery.site) discovery.site = {};
if (!discovery.site.ui) discovery.site.ui = {};



discovery.site.ui.survey = (function(){


	//PRIVATE VARS
	
	var $module = {}, isDisabled = true,
			surveyElem, closeBtn, yesBtn, noBtn,
			SURVEY_URL;
			
	
	//PRIVATE METHODS
	
	function disableSurvey() {
		var date = new Date();
		document.cookie = "DNISURVEY_OPTOUT_NEW=1; domain=."
				+ getRootDomain() + "; path=/; expires="
				+ new Date(date.getFullYear() + 2, 1, 1).toUTCString() + ";";
	}
	
	function hideDialog() {
		surveyElem.style.display = "none";
		return false;
	}
	
	function showSurvey() {
		window.open(SURVEY_URL, "dniSurveyWindow",
				"width=600,height=600,menubar=yes,resizable=yes,scrollbars=yes,status=yes,location=no");
	}
	
	function initCloseBtn() {
		if ((closeBtn)||(closeBtn = getElementsByClassName.call(
				surveyElem, "option-close")[0]))
			addEventListener.call(closeBtn, "click", hideDialog);
	}
	
	function initNoBtn() {
		if ((noBtn)||(noBtn = getElementsByClassName.call(
				surveyElem, "option-no")[0]))
			addEventListener.call(noBtn, "click", function() {
				hideDialog();
				disableSurvey();
				return false;
			});
	}
	
	function initYesBtn() {
		if ((yesBtn)||(yesBtn = getElementsByClassName.call(
				surveyElem, "option-yes")[0]))
			addEventListener.call(yesBtn, "click", function() {
				hideDialog();
				showSurvey();
				disableSurvey();
				return false;
			});
	}
	
	
	//PUBLIC INTERFACE
	
	$module.init = function() {
		if ((!isDisabled)&&(reqsAvailable)) {
			var surveySrc = document.getElementById("dni-survey-popup-scriptblock")
					.innerHTML;
			if (surveySrc) {
				surveyElem = document.createElement("div");
				surveyElem.innerHTML = surveySrc.replace(/[\t\n]*/g, "");
				surveyElem = surveyElem.childNodes[0];
				if (surveyElem) {
					initCloseBtn();
					initYesBtn();	
					initNoBtn();					
					$module.showDialog();
				}
			}
		}
	}
	
	$module.setPopupUrl = function(url) {
		isDisabled = false;		
		SURVEY_URL = url;
	}
	
	$module.showDialog = function() {
		if ((surveyElem)&&(document.body))
			document.body.appendChild(surveyElem);
	}
	
	
	//INITIALISATION
	
	var common, dom, page,
			addEventListener, getElementsByClassName,
			getRootDomain, reqsAvailable;
	
	if ((common = $TORA("common"))
			&&(dom = common.dom)
			&&(page = $TORA("PAGE"))) {
	
		getElementsByClassName = dom.getElementsByClassName;
		addEventListener = dom.addEventListener;
		addEventListener.call(window, "load",$module.init);

				
		//VERIFY REQUIREMENTS
		reqsAvailable = true;
		if (!(getRootDomain = page.getRootDomain))
			reqsAvailable = false;
		
	} else {
		reqsAvailable = false;		
	}
	
	
	return $module;

})();
