/**
 * Created by IntelliJ IDEA.
 * User: mcanas
 * Date: 4/8/11
 * Time: 1:38 PM
 * To change this template use File | Settings | File Templates.
 */

var GlobalNavAlert = (function() {

    var COOKIE_NAME = 'GNA_STATE';
    var COOKIE_DOMAIN = '.constantcontact.com';
    var SHOW_STATE = 0;
    var HIDE_STATE = 1;
    var DAYS_TO_HIDE = 1;
    var DAYS_TO_KILL = 90;

	var head = document.getElementsByTagName('head')[0];
	var body = null;

	// Grab this script element:
	var scripts = document.getElementsByTagName('script');
	var thisScript = scripts[scripts.length-1]; // The current executing script is always the last script

    // Set the url host value
    var HOST = (thisScript.src.indexOf(COOKIE_DOMAIN) !== -1) ? thisScript.src.match(/^https?:\/\/(.*\.com)\//)[1] : null;

	// Set the contentId or kill the script
    var contentId = (HOST) ? thisScript.src.match(/#(.*)?/)[1] : false;

    // Stop executing if the content id is not set
	if(!contentId) {
		return false;
	}

	// A helper function for getting a cookie, if it exists
	function Get_Cookie( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ((!start) && (name != document.cookie.substring(0, name.length))){
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	}

	// A helper function for setting a cookie, only the first 2 parameters are required
	function Set_Cookie( name, value, expires, path, domain, secure ) {
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		// if the expires variable is set, make the correct expires time, the
		// current script below will set it for x number of days, to make it
		// for hours, delete * 24, for minutes, delete * 60 * 24
		if ( expires ){
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" + value  +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	}

    // Attempt to set the state cookie if it does not exist
    if(Get_Cookie(COOKIE_NAME) === null) {
        Set_Cookie(COOKIE_NAME,  SHOW_STATE, 0, '/', COOKIE_DOMAIN);
    }

    // If cookies are turned off by the user or the state cookie is set to the hide state, stop the script from executing
    var state = Get_Cookie(COOKIE_NAME);
    if(state === null || parseInt(state) === HIDE_STATE) {
        return false;
    }

	// Define a getElementsByClassName helper function
	function getElementsByClassName(className, tag, elm){
		var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
		var tag = tag || "*";
		var elm = elm || document;
		var elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
		var returnElements = [];
		var current;
		var length = elements.length;
		for(var i=0; i<length; i++){
			current = elements[i];
			if(testClass.test(current.className)){
				returnElements.push(current);
			}
		}
		return returnElements;
	}

	// A function for hiding the alert
	function hideAlert( days ) {
		body.removeChild(wrapper);
        Set_Cookie(COOKIE_NAME, HIDE_STATE, days, '/', COOKIE_DOMAIN);
	}

	// Create the stylesheet element for the GNA shell
	var shellCSS = document.createElement('link');
	shellCSS.type = "text/css";
	shellCSS.rel = "stylesheet";
    shellCSS.href = "//" + HOST + "/_styles/gna_styles.css";

	head.appendChild(shellCSS);

	// Create the stylesheet element for the content CSS
    var contentCSS = document.createElement('link');
	contentCSS.type = "text/css";
	contentCSS.rel = "stylesheet";
	contentCSS.href = "//" + HOST + "/_styles/gna_" + contentId + "_styles.css";

	head.appendChild(contentCSS);

	// Create the content script element
	var contentScript = document.createElement('script');
	contentScript.type = "text/javascript";
	contentScript.src = "//" + HOST + "/_script/cc.gna-content." + contentId + ".js";

	// Create the wrapper div:
	var wrapper = document.createElement('div');
	wrapper.id = 'gna-wrapper';

	// Create the background div:
	var background = document.createElement('div');
	background.id = 'gna-background';

	// Create the content div:
	var content = document.createElement('div');
	content.id = 'gna-content';

	wrapper.appendChild(background);
	background.appendChild(content);

	// Load the content
	head.appendChild(contentScript);

	function hideEventHandler(event, days) {
        if(!event) {
            window.event.returnValue = false;
        } else {
            event.preventDefault();
        }

        hideAlert(days);
    }

    return {
		setContent : function( options ) {
            // Add the content markup to the GNA shell
			content.innerHTML = options.htmlString;

            // Collect any hide/kill links
			var hiders = getElementsByClassName('gna-hide', 'a', wrapper);
			var killers = getElementsByClassName('gna-kill', 'a', wrapper);
            var popups = getElementsByClassName('gna-popup', 'a', wrapper);

            var i,j;

            // Apply kill event handling to kill links
			if(killers.length > 0) {
				for(i=0, j=killers.length; i<j; i++) {
					killers[i].onclick = function(event) {
                        hideEventHandler(event, DAYS_TO_KILL);
                    }
				}
			}

            // Apply hide event handling to hide links
			if(hiders.length > 0) {
				for(i=0, j=hiders.length; i<j; i++) {
					hiders[i].onclick = function(event) {
                        hideEventHandler(event, DAYS_TO_HIDE);
                    }
				}
			}

            // Apply popup event handling to popup links
			if(popups.length > 0) {
				for(i=0, j=popups.length; i<j; i++) {
					popups[i].onclick = function(event) {
                        hideEventHandler(event, DAYS_TO_HIDE);
                        popHTML(options.popURL,620,520,1);return false;
                    }
				}
			}
		},
		show : function() {
			// Prepend the GNA markup to the body
			body = document.getElementsByTagName('body')[0];
			body.insertBefore(wrapper, body.firstChild);
		},
		hide : function( daysToHide ) { // Public method to hide the alert
			hideAlert(daysToHide);
		},
		kill : function() { // Public method to kill the alert
			hideAlert(DAYS_TO_KILL);
		}
	};
})();
