var Tabs = Class.create({
	initialize: function(container) {
		this.container = $(container) || $("tabs");
		this.togglers  = this.container.select("ul.togglers li");
		this.tabs      = this.container.select("div.tab");
		this.count     = this.togglers.length;
		this.setup();
	},
	setup: function() {
		this.togglers.each(function(el, i) {
			el.observe("click", this.show.bindAsEventListener(this, i)); 
		}.bind(this));
	},
	show: function(event, sel) {
		for (var i = 0; i < this.count; i++) {
			this.deactivate(i);
		}
		this.activate(sel);
		event.stop();
	},
	deactivate: function(pos) {
		this.togglers[pos].removeClassName("active");
		this.tabs[pos].removeClassName("active");
	},
	activate: function(pos) {
		this.togglers[pos].addClassName("active");
		this.tabs[pos].addClassName("active");
	}
});

/* ---------------------------------------------------------------- */
var CommentEditor = Class.create({
	initialize: function(trigger, editor) {
		this.trigger = $(trigger);
		this.editor = $(editor) || $(this.trigger.rev);
		this.cancel = this.editor.select('a.cancel')[0];
		this.reply_form = $('the-reply');
		this.setup();
	},
	setup: function(){
		this.trigger.observe('click', function(event){
			nextdiv = this.trigger.next('div');
			subject = nextdiv.innerHTML;
			comment_class = nextdiv.id.match(/(\S+)_id_(\d+)/)[1];
			comment_id = nextdiv.id.match(/(\S+)_id_(\d+)/)[2];
			this.reply_form.select('i')[0].innerHTML = 'RE: ' + subject;
			this.reply_form.select('#comment_commentable_id')[0].value = comment_id;
			this.reply_form.select('#comment_commentable_type')[0].value = comment_class;
			this.editor.addClassName('edit-mode');
			new Effect.ScrollTo(this.trigger.rev, {offset: -50});
			event.stop();
		}.bind(this));
		this.cancel.observe('click', function(event){
			this.editor.removeClassName('edit-mode');
			event.stop();
		}.bind(this));
	}
});
/* ---------------------------------------------------------------- */


var Accordion = Class.create({
	initialize: function(container) {
		try
		{
			this.container  = $(container);
			this.accordions = $(container).select("div.accordion");
			this.setup();
		} //end of try block
		catch(err){ /* fail gracefully when there is no accordion div */ }
	},
	setup: function() {
		this.unlock();
		this.accordions.each(function(el, i) {
			var toggle = el.down("div.toggler>a");
			if(!!toggle)
			{
			    toggle.observe("click", this.activate.bindAsEventListener(this, i));
		
				if (!toggle.hasClassName("active")) {
					el.down("div.content").setStyle({ display: "none"});
				}
			}
		}.bind(this));
	},
	activate: function(event, sel) {
		if (this.locked) { event.stop(); return; }
		var accordion = this.accordions[sel];
		var toggle    = event.element();
		var content   = accordion.down("div.content");
			
		if (toggle.hasClassName("active")) {
			document.fire("accordion:closed");
			toggle.removeClassName("active");
			Effect.BlindUp(content, {
				duration:    0.4,
				beforeStart: this.lock.bind(this),
				afterFinish: this.unlock.bind(this)
			});
		} else {
			document.fire("accordion:opened");
			toggle.addClassName("active");
			Effect.BlindDown(content, {
				duration:    0.4,
				beforeStart: this.lock.bind(this),
				afterFinish: this.unlock.bind(this)
			});
		}
		event.stop();
	},
	lock: function() {
		this.locked = true;
	},
	unlock: function() {
		this.locked = false;
	}
});


/* ---------------------------------------------------------------- */

var PopOut = Class.create({
	initialize: function(trigger, target) {
		this.trigger = $(trigger);
		this.target  = $(target);
		this.setup();
	},
	setup: function() {
		this.trigger.observe("click", this.flip.bindAsEventListener(this));
	},
	flip: function(event) {
		this.target.toggleClassName("active");
		if (event){event.stop();}
	}
});

/* --------------------------------------------------------------- */

/* TODO: Callouts seem to break when elements with callouts have an ID */
var CallOut = Class.create({
	initialize: function(trigger, callout) {
		this.container = $('container');
		this.trigger = $(trigger);
		this.callouts  = $('callouts');
		this.callout = $(callout);
		this.overlay = $('overlay');
		this.cancel = (this.callout.select('a.cancel')[0] || this.callout.select('a.close')[0] || this.callout.select('a.x-close')[0] || false);
		this.setup();
	},
	setup: function() {
        this.trigger.observe("click", this.open.bindAsEventListener(this));
        this.overlay.observe("click", this.close.bindAsEventListener(this));
        if(this.cancel){ 
					this.cancel.observe("click", this.close.bindAsEventListener(this));
				}
	},
	open: function(event) {
        this.callouts.setOpacity(1);
        this.callout.style.visibility = 'visible';
        this.callouts.setStyle({'height': this.container.offsetHeight + 'px'});
        this.callouts.style.display ='block';
        this.callout.style.display ='block';
        if (event){event.stop();}
	},
	close: function(event) {
		new Effect.Fade(this.callouts, {duration: 0.3, from: 0.3, to: 0.0, afterFinish: function(){
			this.callouts.style.display = 'none';
			this.callout.style.display = 'none';
			this.callout.style.visibility = 'hidden';
		}.bind(this)});
		if(event) {
			event.stop();
		}
	}
});

/* --------------------------------------------------------------- */

var Filter = Class.create(PopOut, {
	initialize: function(trigger, target, results) {
		this.trigger    = $(trigger);
		this.target     = $(target);
		this.results    = $(results);
		this.form       = this.target.down("form");
		this.options    = this.target.select("div.option");
		this.checkboxes = this.target.select("div.option input.checkbox");
		this.select     = this.target.down("a.select-all");
		this.deselect   = this.target.down("a.select-none");
		this.total      = this.options.length;
		this.close      = this.target.select('a.x')[0];
		this.setup();
	},
	setup: function($super) {
		this.select.observe("click", this.select_all.bindAsEventListener(this));
		this.deselect.observe("click", this.select_none.bindAsEventListener(this));
		this.close.observe("click", this.flip.bindAsEventListener(this));
		this.form.observe("submit", this.submit.bindAsEventListener(this));
		this.options.each(function(el) {
			el.observe("click", this.toggle.bindAsEventListener(this))}.bind(this));
		this.checkboxes.each(function(el, i) {
			el.checked = this.options[i].hasClassName("checked"); }.bind(this));
		$super();
	},
	select_all: function(event) {
		for (var i = 0; i < this.total; i++) {
			this.options[i].addClassName("checked");
			this.checkboxes[i].checked = true;
		}
		event.stop();
	},
	select_none: function(event) {
		for (var i = 0; i < this.total; i++) {
			this.options[i].removeClassName("checked");
			this.checkboxes[i].checked = false;
		}
		event.stop();
	},
	toggle: function(event) {
		var option   = event.findElement("div.option");
		var checkbox = option.down("input.checkbox");
		
		option.toggleClassName("checked");
		checkbox.checked = !checkbox.checked;
		
		event.stop();	
	},
	submit: function(event) { 
	  if(!this.results){ return true; }
		new Ajax.Updater(this.results, this.form.action, {
		  method:     this.form.action,
		  parameters: this.form.serialize(),
		  onComplete: function() {
		    this.flip(false);
		  }.bind(this) 
		});
		event.stop();
	}
});

/* ---------------------------------------------------------------- */

var Prompt = Class.create({
	initialize: function(field) {
		this.field = $(field);
		this.setup();
	},
	setup: function() {
		this.field.observe('focus', this.focus.bind(this));
		this.field.observe('blur', this.blur.bind(this));
	},
	focus: function() {
		if (this.field.value == this.field.defaultValue) {
			this.field.value = '';
		}
	},
	blur: function() {
		if (this.field.value === '') {
			this.field.value = this.field.defaultValue;
		}
	}
});

/* ---------------------------------------------------------------- */

var SearchSuggestion = Class.create({
	initialize: function(field, url, suggestion) {
		this.field = $(field);
		this.suggestion = $(suggestion) || $('search-suggestions');
		this.url = url;
		this.setup();
	},
	setup: function(){
		new Ajax.Autocompleter(this.field, this.suggestion, this.url);
	}
});

/* ---------------------------------------------------------------- */

var PostComment = Class.create(PopOut, {
	initialize: function(trigger, target) {
		this.trigger = $(trigger);
		this.target  = $(target);
		this.options      = this.target.select("div.option");
		this.cancel_btn   = this.target.down("a.cancel");
		this.setup();
	},
	setup: function($super) {
		this.options.each(function(el) {
			el.observe("click", this.toggle.bindAsEventListener(this))}.bind(this));
		this.cancel_btn.observe("click", this.flip.bindAsEventListener(this));
		$super();
	},
	toggle: function(event) {
		var option   = event.findElement("div.option");
		var checkbox = option.down("input.checkbox");		
		option.toggleClassName("checked");
		checkbox.checked = !checkbox.checked;		
		event.stop();
	}
});

/* ---------------------------------------------------------------- */

var LoginCallout = Class.create(CallOut, {
	open: function($super, event) {
		this.error = this.callout.select('p.error')[0];
		this.registration = $('registration-callout-form');
		if(this.trigger.rel != 'must') {
			this.error.setOpacity(0);
		}
		if(this.trigger.rel == 'must'){
			this.error.setOpacity(1);
		}
		if(this.trigger.rel == 'thanks'){
			this.callout.addClassName('thanks')
		}
		// this.registration.observe('submit', function(event){
		// 	event.stop();
		// 	this.callout.addClassName('thanks');
		// }.bind(this));
		$super(event);
	}
});

/* ----------------------------------------------------------------- */
var FeedbackCallout = Class.create(CallOut, {
	open: function($super, event) {
		this.error = this.callout.select('p.error')[0];
		this.registration = $('feedback-callout-form');
		this.callout.setOpacity(1);
		if(this.trigger.rel == 'thanks'){
			this.callout.addClassName('thanks')
		}
		$super(event);
	}
});

/* ----------------------------------------------------------------- */

function createjscssfile(filename, filetype){
  var fileref;
	if (filetype=="js"){ //if filename is a external JavaScript file
  	fileref=document.createElement('script');
  	fileref.setAttribute("type","text/javascript");
  	fileref.setAttribute("src", filename);
 	}
 	else if (filetype=="css"){ //if filename is an external CSS file
  	fileref=document.createElement("link");
  	fileref.setAttribute("rel", "stylesheet");
  	fileref.setAttribute("type", "text/css");
  	fileref.setAttribute("href", filename);
 	}
 	return fileref;
}

function load_map_widget(){
	filename = '/javascripts/maps/frontend-maps.js'
	oScript = createjscssfile(filename,'js');
	// IE 6 & 7
	if(navigator.appName == "Microsoft Internet Explorer"){
		oScript.onreadystatechange = function() {
			if (this.readyState == 'loaded' || this.readyState == 'complete') {
  			initializeFrontendMap();
			}
		}
	}else{
		// most browsers
		oScript.onload = initializeFrontendMap;
	}
  document.getElementsByTagName("head")[0].appendChild(oScript);
}

function map_js_loader(){
	
  new Ajax.Request( '/frontend_maps/get_gmap_api_key', {
		onComplete: function(transport){
			var gmap_url = 'http://maps.google.com/maps?file=api&v=2.x&' + transport.responseText + '&async=2&callback=load_map_widget&sensor=false';
      oMapjs = createjscssfile( gmap_url,'js');
			document.getElementsByTagName("head")[0].appendChild(oMapjs);
    }
  });

}
var MapCallout = Class.create(CallOut, {
  open: function($super, event) {
    new Ajax.Updater({ success: this.callout.select("div.content")[0] }, this.trigger.rel, {
  		onComplete: function(transport){
        //TODO: need to move this to NeighborhoodCallout
				$super(event)
				map_js_loader()
        //TODO: onFailure, provide feedback
      }
    });
	}
});

var SelectionCallout = Class.create(CallOut,{
  setup: function() {
        this.trigger.observe("change", this.open.bindAsEventListener(this));
        this.overlay.observe("click", this.close.bindAsEventListener(this));
        if(this.cancel){ this.cancel.observe("click", this.close.bindAsEventListener(this)); }
	},
	open: function($super, event) {
		var url = "";
		if (this.trigger.getAttribute('rel') !== null){
			url = this.trigger.getAttribute('rel');
		}
		url += this.trigger.value;
		new Ajax.Updater({success: this.callout.select("div.content")[0] }, url, {
     	onComplete: function(transport){
				$super(event);
				map_js_loader();
	  	}
		});	
	}
});

/* ---------------------------------------------------------------- */

var Report = Class.create({
	initialize: function(trigger, id){
		this.container = $('container');
		this.callout = $(id) || false;
		this.trigger = $(trigger);
		this.id = id || false;
		this.report_id = id.match(/(\S+)_id_(\d+)/)[2];
		this.report_type = id.match(/(\S+)_id_(\d+)/)[1];
		if (this.report_type == 'comment'){
			this.report_url = '/comments/'
		}
		else{
			this.report_url = '/tips/'
		}
		if(this.callout){
			this.callout = $(this.id);
			this.cancel = this.callout.select('a.no')[0];
			this.confirm = this.callout.select('a.report')[0];
			this.setup();
		}
	},
	setup: function(){
		this.confirm.observe("click", this.report.bindAsEventListener(this));
		this.cancel.observe("click", this.close.bindAsEventListener(this));
	},
	report: function(event){
		new Ajax.Request(this.report_url + 'report?report_id='+this.report_id)
		this.close(event);
		event.stop();
	},
	open: function(event){
		if(!this.callout){
			new Ajax.Request(this.report_url + 'report_confirm?report_id='+this.report_id, {
				onComplete: function(transport){
					var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/;
					var html = transport.responseText.interpolate({id: this.id}, syntax);
					var position = { top: this.trigger.cumulativeOffset().top, left: this.trigger.cumulativeOffset().left };
					this.container.insert({After: html});
					this.callout = $(this.id);
					this.callout.style.top = (position.top-20)+'px';
					this.callout.style.left = (position.left+65)+'px';
					this.cancel = this.callout.select('a.no')[0];
					this.confirm = this.callout.select('a.report')[0];
					this.setup();
					this.callout.show();
				}.bind(this)
			});
		} else {
			this.callout.show();
		}
		event.stop();
	},
	close: function(event){
		this.callout.hide();
		event.stop();
	}
});

/* ---------------------------------------------------------------- */


//MKP: Moved these two .instances out of the dom:loaded block below... these need
//to happen before the page finishes loading, so that if someone clicks
//an ajax link that returns somethign trying to call LoginCallout.instances
//before the page finishes loading, it still works. before, it would silently
//fail because LoginCallout.instances wasn't set up until the page was fully loaded. 
LoginCallout.instances = [];
FeedbackCallout.instances = [];


document.observe("dom:loaded", function(){
    // Added a local for error messages
    var err;
    
	$$("input.prompt").each(function(el) {
		new Prompt(el);
	});
         
	if($$('a.report').length > 0){
		$$('a.report').each(function(el, i){
			var o = {};
			el.observe('click', function(event){
				if(!o[i]){ o[i] = new Report(el, el.rel); }
				o[i].open(event);
			});
		});
	}
         
        /*MKP: I'm commenting this out since it makes for a really annoying UI 
              (the page scrolls to the top at the end of the page load to focus 
               the search box input, which will drive you crazy if you're already 
               scrolling down the screen)*/
        /* Focus on the first input field on all frontend pages */
        /*$$("input")[0].focus();*/

        //LoginCallout.instances = [];
        //FeedbackCallout.instances = [];


  /*MKP: Commenting this out for now - I'm trying to make this happen conditionally on pages
          with comments (via an AJAX call that happens on load), so that we can cache those
          pages. 
  */
	/*if($('login-callout')){
		$$('a.login-callout-trigger').each(function(el){
			LoginCallout.instances.push(new LoginCallout(el, 'login-callout'));
		});
	}*/

	if($('feedback-callout')){
		$$('a.feedback-callout-trigger').each(function(el){
			FeedbackCallout.instances.push(new FeedbackCallout(el, 'feedback-callout'));
		});
	}
	
	/* AddThis Bookmark */
	if($$('a.bookmark').length > 0){
		addthis_pub             = 'TravelLeisure'; 
		addthis_logo            = '/images/logo/travel-leisure.gif';
		addthis_logo_background = '112266';
		addthis_logo_color      = 'ffffff';
		addthis_options         = 'favorites, email, google, delicious, buzz, digg, facebook, live, more';

		$$('a.bookmark').each(function(el){
			el.observe('mouseover', function(event){
				// prevent third party link from loading in our browser window
				$$("a[title=AddThis]").each(function(el2){el2.target = "_blank";});
				return addthis_open(el, '', document.location.href, document.title);
			});
			el.observe('mouseout', function(event){
				addthis_close();
			});
			el.observe('click', function(event){
				return addthis_sendto();
			});
			//el.href = 'http://www.addthis.com/bookmark.php'; //preventing this page to open in new tab
            //el.target = '_blank'; // prevent third party link from loading in our browser window
			el.onclick = 'void(try{void(addthis_sendto("more"));}catch (var err){ return false;})';
		});

/*      We're not using the the AddThis(TM) email functionality */
//		$$('a.email').each(function(el){
//			el.observe('mousein', function(event){
//				addthis_open(el);
//				//return addthis_sendto('email');
//			});
//            el.observe('mouseover', function(event){
//                return addthis_sendto('email');
//            });
//			el.observe('click', function(event){
//				addthis_close();
//			});
//		});

		var addThisScript = new Element('script', {type: 'text/javascript', src: 'http://s7.addthis.com/js/152/addthis_widget.js' });
		$('container').insert({after: addThisScript});
		
	}

	if($$('a.print').length > 0){
		$$('a.print').each(function(el, i){
			el.observe('click', function(event){
				event.stop();
				window.print();
			});
		});
	}
  
  //this method allows for external links to popup in a new window/tab
  externalLinks();
  
  // AFC sub-menu initialization 
  // Added for native AFC implementation [2009-09-24, A.Lewis]
  if($$('#menu ul.dropdown').length > 0)
  {
      try
      {
          initMenu();
      }
      catch(err){ /* fail gracefully */ }
  }
        
    //var selectionCallout;
//    if ($$('select.neighborhood-callout-trigger')[0]){
//      selectionCallout = new SelectionCallout($$('select.neighborhood-callout-trigger')[0],'ajax-callout');
//    }
});


/* ---------------------------------------------------------------- */


// forms that call AJAX objects don't reload the page,
// so their submit buttons need to be disabled temporarily
// to prevent double submissions
function buttonCoolDown(e)
{
	// INITIALIZE: get the event's source from the event 
	if(!e){ var e = window.event; }
	var theButton;
	if (e.target){ 
		theButton = e.target; 
	}else if (e.srcElement){ 
		theButton = e.srcElement; 
	}
	
	if (theButton.nodeType == 3){
	 	// defeat Safari bug
	  theButton = theButton.parentNode;
	}
	// FILTER: affect only form buttons
	if(!(theButton.tagName.toLowerCase() == "input" && "button|image|submit".indexOf(theButton.type.toLowerCase()) != -1) && !!theButton.form){
	    return;
	}
	
	// ACT: disable the button for a while
	theButton.disabled = true;
	if(!theButton.id || theButton.id === ""){
		theButton.id = "button_" + parseInt(Math.random()*10000, 10);
	}
	window.setTimeout("document.getElementById('" + theButton.id + "').disabled = false",10000);
	
	// CLEANUP: some browsers won't submit if the 
	// onclick event has a handler set so we need
	// to fire the form's onsubmit event handler
	// to make the AJAX call.
	if(Prototype.Browser.IE || Prototype.Browser.Opera || Prototype.Browser.WebKit){
	    theButton.form.onsubmit();
	}
}


/* ---------------------------------------------------------------- */

      
// Original published under CC-GNU LGPL license by Dustin Diaz
// with a fix for an IE memory leak if events are removed
function addEvent( obj, type, fn )
{
    if (obj.addEventListener) 
    {
        // standard
        obj.addEventListener( type, fn, false );
        EventCache.add(obj, type, fn);
    } 
    else if (obj.attachEvent) 
    {
        // IE
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
        EventCache.add(obj, type, fn);
    } 
    else 
    {
        // really old
        obj["on"+type] = obj["e"+type+fn];
    }
}
    
// Original published under CC-GNU LGPL license by Dustin Diaz
// as a fix for an IE memory leak if events are removed
function removeEvent( obj, type, fn )
{
    EventCache.remove(obj, type, fn);
}

// Original published under CC-GNU LGPL license by Dustin Diaz
// as a fix for an IE memory leak if events are removed
var EventCache = function()
{
    var listEvents = [];
    return { // DON'T put the preceding  brace on another line, or it'll break the statement
    listEvents : listEvents,
    add : function(node, sEventName, fHandler)
    {
        listEvents.push(arguments);
    },
        remove : function(node, sEventName, fHandler)
        {
            var i, item;
            for(i = listEvents.length - 1; i >= 0; i = i - 1) 
            {
                if(node == listEvents[i][0] && sEventName == listEvents[i][1] && fHandler == listEvents[i][2]) 
                {
                    item = listEvents[i];
                    if(item[0].removeEventListener) 
                    {
                        item[0].removeEventListener(item[1], item[2], item[3]);
                    }
                    if(item[1].substring(0, 2) != "on") 
                    {
                        item[1] = "on" + item[1];
                    }
                    if(item[0].detachEvent) 
                    {
                        item[0].detachEvent(item[1], item[0][sEventName+fHandler]);
                    }
                    item[0][item[1]] = null;
                }
            }
        },
        flush : function()
        {
            var i, item, eventtype;
            for(i = listEvents.length - 1; i >= 0; i = i - 1) 
            {
                item = listEvents[i];
                if(item[0].removeEventListener) 
                {
                    item[0].removeEventListener(item[1], item[2], item[3]);
                }
                eventtype = item[1];
                if(item[1].substring(0, 2) != "on") 
                {
                    item[1] = "on" + item[1];
                }
                if(item[0].detachEvent) 
                {
                    item[0].detachEvent(item[1], item[2]);
                    item[0].detachEvent(item[1], item[0][eventtype+item[2]]);
                }
                item[0][item[1]] = null;
            }
        }
    }
}();
addEvent(window,'unload',EventCache.flush);



/* ---------------------------------------------------------------- */

// Used to insure a link meant to invoke an AJAX
// call from the onclick event isn't followed, 
// as "return false" will fail on some browser versions
function cancelEvent(e)
{
    if (!e){ var e = window.event; }
    if (e.stopPropagation){ e.stopPropagation(); }
    if (e.preventDefault){ e.preventDefault(); }
    if (e.cancelBubble){ e.cancelBubble = true; }
    if (e.returnValue){ e.returnValue = false; }
    return false;
}


/* ---------------------------------------------------------------- */



//registration form callout submit
function userRegister()
{
    userForm = $('user-register') ? $('user-register') : $('registration-callout-form');
    userOption = 2;
    userRefPg = userForm.elements["referrer"].value;
    var token = userForm.elements["authenticity_token"];
    if(token && token.type == "hidden"){
      token.value = encodeURIComponent(token.value);
		}
    userRequest(userForm.action);
}

function userRequest(url)
{   
    formConnection = new Ajax.Request(url, {
         asynchronous: true,
         evalScripts: true,
         method: 'post',
         parameters: userForm.serialize(true) ,
         onSuccess: function (transport) {
             var r = transport.responseText;
             var s = transport.status;
             var h = transport.getHeader("X-AJAX-RESPONSE") || '';
             //debug
             //window.alert('Transport Status: "' + s + '"\nX-AJAX-RESPONSE header: "' + h.toLowerCase() + '"' );
             // handle the response
             if(s === 0){ /* Bail! (Connection Problem) */ window.location.href = userRefPg; }
             switch(userOption)
             {
                 case 1:  
                 { 
                    if(h.toLowerCase() == "logged")
                    {
                        //Logon Success
                        try
                        {
                            err = $$('#login-callout p.error').first()
                            err.update('Logon Success!')
                            err.setOpacity(1);
                        }
                        catch(jserr) { alert('Logon Success.\n[js statements failed though: ' + jserr.message + ']'); }
                        
                    }
                    else
                    { 
                        //Logon Failure
                        try
                        {
                            err = $$('#login-callout p.error').first()
                            err.update('Invalid login or password.')
                            err.setOpacity(1);
                        }
                        catch (jserr){ alert('Invalid login or password.\n[js statements failed as well: ' + jserr.message + ']') }
                    }
                    break; 
                 }
                 case 2:  
                 { 
                    if(h.toLowerCase() == "logged")
                    {
                        //Registration/Logon Success
                        try
                        {
                            err = $$('#login-callout p.error').first()
                            err.update('Logon Success!')
                            err.setOpacity(1);
                        }
                        catch(jserr) { alert('Registration/Logon Success.\n[js statements failed though: ' + jserr.message + ']'); }
                        
                    }
                    else
                    { 
                        //Registration/Logon Failure
                        try
                        {
                            err = $$('#login-callout p.error').first()
                            err.update('Invalid login or password.')
                            err.setOpacity(1);
                        }
                        catch (jserr){ alert('Registration or Logon Failed.\n[js statements failed as well: ' + jserr.message + ']') }
                    }
                    break; 
                 }
                 default: { /* success */ break; }
             }
             //alert(userRefPg);
             //window.location.href = userRefPg;
         },
         onFailure: function (transport) {
             var r = transport.responseText;
             // handle the response
             switch(userOption)
             {
                 case 1:  { window.alert('Logon Connection Failure: ' + r);  break; }
                 case 2:  { window.alert('Registration failure: ' + r); break; }
                 default: { /* failure */ break; }
             }
             //alert(userRefPg);
             //window.location.href = userRefPg;
         },
         onCreate: function (transport)
         {
             //window.alert('Ajax Request Parameters: ' + unescape(userForm.serialize()));
         },
         onException: function (request, exception)
         {
             window.alert('Ajax Request Exception: ' + exception);
         }
         
     });
}

//this method allows for external links to popup in a new window/tab
function externalLinks()
{
    $$("a.external").each(function(link){ link.target = "_blank"; });
}

// set a cookie
function setCookie(sName, sValue, sExpires, sPath, sDomain, secure) 
{ 
    document.cookie = sName + "=" + escape(sValue) + (sExpires === null ? "" : ";expires=" + sExpires.toGMTString()) + (sPath === null ? "" : ";path=" + sPath ) + (sDomain === null ? "" : ";domain=" + sDomain) + (secure === null ? "" : ";secure");
}

// get a cookie (returns string)
function getCookie(sName) 
{ 
    var search = sName + "=";

    // if there are any cookies
    if (document.cookie.length > 0) 
    { 
        offset = document.cookie.indexOf(search);

        // if cookie exists 
        if (offset != -1) 
        {  
            // set index of beginning of value
            offset += search.length; 

            // set index of end of cookie value
            end = document.cookie.indexOf(";", offset);

            if (end == -1){ end = document.cookie.length; }
            return unescape(document.cookie.substring(offset, end));
        }

        else 
        {
            return "";
        } 
    }
}

// delete a cookie (if path and/or domain were set to other than default
// when the cookie was written, matching arguments must be passed here.)
function deleteCookie(sName, sPath, sDomain)
{
    if(document.cookie.length > 0 && document.cookie.indexOf(sName) != -1)
    {
        var oldDate = new Date();
            oldDate.setYear(oldDate.getFullYear() - 20);
        document.cookie = sName + "=;expires=" + oldDate.toGMTString() + (sPath === null ? "" : ";path=" + sPath) + (sDomain === null ? "" : ";domain=" + sDomain);
        eval("var re = /" + sName + "\=[^;]*(;|$)/gi;");
        document.cookie = document.cookie.replace(re,"");
    }
}
/* ---------------Slideshow Autoplay Functions------------------------------------------------- */
function doTimer(nexturl, t, state)
{
	var state = (state === undefined) ? "on" : state;
	var timeoutPeriod = 30000;
	url = nexturl;
	t=setTimeout("window.location=url;",timeoutPeriod);
	if (state=='off') {clearTimeout(t);} //no timeout need for default 'off' state
	
    try{
	    var size = 0;
	    //while(size == 0){

	    pauseButtons = $$('div[class=pause]');
		playButtons = $$('div[class=play]');
	    
		pauseButtons.each(function(s, index) {
			if (state == 'on') {
			  s.show();
			}
			else {
			  s.hide();
			}
		});

		playButtons.each(function(s, index) {
			if (state == 'on') {
			  s.hide();			
			}	
			else {
			  s.show();
			}		
		});
		//alert('from doTimer'+"t:" + t);
		//}
 
    }
    catch(err){
		window.alert(err.message);
    }
	//setCookie('autoplay', 'on', '', '/');
	setCookie('autoplay', state);
	return t;
}

function stopCount(t)
{
	clearTimeout(t);

    try{
	    var size = 0;
	    //while(size == 0){
		pauseButtons = $$('div[class=pause]');
		playButtons = $$('div[class=play]');
		
		pauseButtons.each(function(s, index) {
			s.hide();
		});

		playButtons.each(function(s, index) {
			s.show();
		});
		
		//alert('from stopCount'+"t:" + t);
		
		//}
    }
    catch(err){
		window.alert(err.message);
    }
	// /setCookie('autoplay', 'off', '', '/');
	setCookie('autoplay', 'off');
	return t;
}
/* ---------------end --- Slideshow Autoplay Functions------------------------------------------------- */

