var PageAlert = function(opts) {
	var pa = this;
	pa.opts = opts;
  pa.page_alert_wrapper = $('.page-alert-wrapper');
	pa.page_alert = $('.page-alert-message');
	pa.alert_states = {'NotViewed': 0, 'Viewed': 1};
  pa.alert_dismiss_click = function(evt) { pa.hideAlert(); } 
  pa.alert_dismiss_key = function(evt) { if(evt.which == 27) pa.hideAlert(); }	
	
	// make sure state is set to NotViewed for pages without an active alert
	if(!pa.opts.AlertActive) pa.setState(pa.alert_states.NotViewed);
	
	if(pa.opts.AlertActive && (!pa.hasBeenViewed() || pa.opts.AlwaysShow)) {
		if(parseFloat(pa.opts.Delay)) {
			setTimeout("pa.showAlert()", pa.opts.Delay * 1000);
		} else {
			pa.showAlert();
		}
	}
}
PageAlert.prototype.getState = function() {
    var nameEQ = "alert_state=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
PageAlert.prototype.hasBeenViewed = function() {
	return (this.getState() == this.alert_states.Viewed) ? true : false;
}
PageAlert.prototype.setState = function(state) {
    var date = new Date();
	date.setTime(date.getTime()+(365*24*60*60*1000));
    document.cookie = "alert_state=" + state + "; expires="+date.toGMTString() + "; path=/";
}
PageAlert.prototype.hideAlert = function() {
    pa.page_alert.hide();
    pa.page_alert_wrapper.hide();
    $("body").unbind("keyup", pa.alert_dismiss_key);
}
PageAlert.prototype.showAlert = function() {
	this.setState(this.alert_states.Viewed);
	this.page_alert_wrapper.detach().prependTo("body").show();
  this.page_alert.detach().prependTo("body").show();
  this.page_alert.append('<div class="controls"><input type="submit" value="OK" id="page-alert-dismiss" /></div>');
  
  $("#page-alert-dismiss").live("click", this.alert_dismiss_click);
  $("body").live("keyup", this.alert_dismiss_key);
}
PageAlert.prototype.debug = function() {
	if(console != undefined) {
		console.log("IsActive: " + this.opts.AlertActive);
		console.log("HasBeenViewed: " + this.hasBeenViewed());
		console.log("AlwaysShow: " + this.opts.AlwaysShow);
		console.log("CurrentState: " + this.getState());
	}
}


$(function(){
	pa = new PageAlert(page_alert_options);
});

