var map_counter = 0; 
/**
 *
 */
function initializeMap() {
	if (GBrowserIsCompatible()) {
		/***
		var map = new GMap2(document.getElementById("map_canvas"))
		map.setCenter(new GLatLng(37.4419, -89.1419), 3);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		***/
		var map = new GMap2(document.getElementById("map_canvas"));
			map.setCenter(new GLatLng(37.4419, -89.1419),3);
			map.addControl(new GSmallMapControl());
		geocoder = new GClientGeocoder();			
		baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);
		showAddress(map);
	}
};
/**
 *
 */
function showAddress(map) {
	if (geocoder) {
		map_zoom = 3; 
		for(i=0;i<address.length; i++) {
			geocoder.getLatLng(
			 address[i],
				function(point) {
					if (point) {
						map.setCenter(point, map_zoom);
						map.addOverlay(createMarker(point, i));
					}
				}
			);
		};
	}
};
/**
 *
 */
function createMarker(point, index) {
	var number = map_counter; 
	var letter = String.fromCharCode("A".charCodeAt(0)+map_counter);
	var icon = new GIcon(baseIcon);
	icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		if(enableMapClick) window.open(urls[number]); 	
	});
	map_counter++; 
	return marker;
};
/**
 * Reset fields on event search form. 
 */
function resetFields(){
	$$('#f-meetings select').each(function(item,index){
		item.selectedIndex = 0; 
	}); 
	$('u_city').value='-- City Search --'; 
	$('u_evq').value='-- Keyword Search --'; 
};

/**
 *
 */
function peerclip() {
	window.open('http://www.peerclip.com/bookmarks/add?ref=cecentral&amp;reference_item[uri]='+ encodeURIComponent(location.href)+'&bookmark[title]='+encodeURIComponent(document.title)); 
};

/**
 *
 */
function u_print(){
	window.print(); return false; 
};

/**
 * Execute AJAX Request for activity page tabs
 * @param string str
 */
function activityPage(id,str,params) {
	$$('div.nav li').each(function(item,index){
		if(item.hasClass('t-'+str)) {

			item.addClass('active');
		} else { 
			item.removeClass('active');
		}
	});
	indicate(1);
	var params = params!=undefined ? params : ''; 
	var url = uri+'index.php?tpl=activity&aid='+id+'&v='+str+params; 
	var ajx = new Ajax(url,{evalScripts:'true',method:'get',update:'content',onComplete: function(){indicate(0); /*actArrowFade();*/}}).request();
};

/**
 * Load presenter 3.0 in a new window
 * @param string uri
 */
function activityLoadPresenter(uri)
{
    var width = Math.round(screen.width * 0.80);
    var height = Math.round(screen.height * 0.80);
    var top = Math.round((screen.height - height) / 2);
    var left = Math.round((screen.width - width) / 2);
    var options = "width=" + width + ",height=" + height + "top=" + top + ",left=" + left + ",toolbars=no,location=no,status=no";
    //alert(uri + ' ' + options);
    var presenter = window.open(uri,"cec_presenter",options);
    presenter.focus();
}

/**
 * Change active activity page tab based on arrow click
 * @param int dir - direction in which to go. 1 is forward; -1 is back
 */
function actArrowStep(dir){
	var activeTab = 0;
	var tabs = $$('ul.tab li.actstep');
	tabs.each(function(li,i){
		if(li.hasClass('active'))
			activeTab = parseInt(li.id.substr(4))-1;
		if(i==tabs.length-1)
			li.addClass('last');
	});

	var ceiling = tabs.length-1;
	if( (dir > 0 && activeTab+dir <= ceiling) || (dir < 0 && activeTab+dir >= 0) ){
		tabs[activeTab].removeClass('active');
		activeTab = parseInt(activeTab+dir);
		tabs[activeTab].addClass('active');
	}
	
	if(!window.actArrowInit){
		window.actArrowInit = true;
	}else{
		var links = $$('ul.tab li.actstep a');
		var linkActions = {};
		links.each(function(a,i){
			linkActions[i] = a.onclick;
		});
		
		linkActions[activeTab]();
	}

	actArrowFade();
}

/**
 * Adjust opacity of activity page navigation arrows based on active tab
 */
function actArrowFade(){
	var activeTab = 0;
	var tabs = $$('ul.tab li.actstep');
	tabs.each(function(li){
		if(li.hasClass('active'))
			activeTab = parseInt(li.id.substr(4))-1;
	});
	var ceiling = tabs.length-1;
	if(activeTab == 0) //if we're at zero, fade out the back button
		new Fx.Styles($('tabClickBack'), {duration:200, wait:false}).start({'opacity':0.5});			
	else if(activeTab != 0 && $('tabClickBack').getStyle('opactiy') != 1.0) //if we aren't at 0, and the back button isn't opaque, make it that way
		new Fx.Styles($('tabClickBack'), {duration:200, wait:false}).start({'opacity':1.0});
	
	if(activeTab == ceiling) //if we're at ceiling, fade out the next button
		new Fx.Styles($('tabClickNext'), {duration:200, wait:false}).start({'opacity':0.5});
	else if(activeTab != ceiling && $('tabClickNext').getStyle('opactiy') != 1.0) //if we aren't at ceil, and the next button isn't opaque, make it that way
		new Fx.Styles($('tabClickNext'), {duration:200, wait:false}).start({'opacity':1.0});
}

/**
 * toggles display decl. for indicator img
 * @param boolean indication
 */
function indicate(indication){
	$$('.indicator-inner').each(function(e){
        e.effect('opacity',{duration:100}).start(indication?(0,1):(1,0));         
    });
};

/**
 * Toggles search box UI type selector
 * @param string
 */
function search_type(q,k,el) {
	$('u_qtype').value = q; 
	$('u_q').value = k; 
	el = !el ? 'all' : el;
	$$('#search li').each(function(item,index) {
		item.removeClass('active'); 
		if(item.getAttribute('id')==el) { item.addClass('active'); }; 
	}); 
}; 

/**
 * Uses params to build search url
 */
var advSearch = new Class ({
	initialize: function(uri) {
		this.opt(uri); 
	},
	opt: function(uri) {
		this.uri = uri;
	},
	set_params: function(search_type,param1,param2) {
			if(search_type) this.search_type = search_type;
			if(param1) this.param1 = param1;
			if(param2) this.param2 = param2;
	},
	set_form_params: function(search_type,param1,param2) {
			if(search_type)this.search_type = $(search_type).value; 
			if(param1) this.param1 = $(param1).value;
			if(param2) this.param2 = $(param2).value;
	},
	do_search: function(search_type,param1,param2) {
		var uri = ''; 
		if(this.search_type=='events') {
			uri = this.uri+'event/search/'; 
			uri += this.param2 ? this.param2: '';
		} else {
			uri = this.uri+'search/';
			uri += this.search_type ? this.search_type : '';
			uri += this.param1 ? '/'+this.param1 : '';
			uri += this.param2 ? '/'+this.param2: '';
		}
		window.location.href = uri;
	}
	 
});

/**
 * Opens a modal window
 * @param string str Can be either url or string to be displayed in modal window, but cannot cross domains
 * @param string caption
 * @param integer width
 * @param integer height
 * @param 
 */
var closeable = true;
function modal(str,caption,width,height) {
	caption = caption==undefined ? '' : caption; 
	width = width==undefined ? 500 : width; 
	height = height==undefined ? 400 : height; 
	MOOdalBox.open(str,caption,width+" "+height);
};

/**
 * Opens a modal dialog box with save,close buttons
 * @param string str Can be either url or string to be displayed in modal window, but cannot cross domains
 * @param string action JS action to execute onclick of save btn
 * @param integer width
 * @param integer height
 * @param 
 */
function modal_d(str,action,btnLabel,width,height) {
	$('mb_contents').removeClass('noscroll');
	$('mb_bottom').removeClass('nodisplay');
	$('mb_overlay').removeClass('nopointer');
	action = action==undefined ? 'void(0)' : action;
	btnLabel = btnLabel==undefined ? 'Save' : btnLabel;  
	width = width==undefined ? 500 : width; 
	height = height==undefined ? 400 : height; 
	MOOdalBox.openDialog(str,action,btnLabel,width+" "+height);
};


/**
 * Opens a modal dialog box with embedded iframe
 * User cannot manually close this modal box, the url loaded in the iframe must have an action calling parent.modal_iclose() method
 * @param string str Can be either url or string to be displayed in modal window, but cannot cross domains
 * @param string caption
 * @param integer width
 * @param integer height
 * @param 
 */
function modal_i(str,caption,width,height) {
	closeable = false;
	caption = caption==undefined ? '' : caption; 
	width = width==undefined ? 500 : width; 
	height = height==undefined ? 400 : height; 
	MOOdalBox.open('<iframe name="ifr" id="ifr" src="'+str+'" width="'+width+'" height="'+height+'" frameborder="0" marginheight="0" marginwidth="0">if you can see this, pound sand.</iframe>',caption,width+" "+height); 
	$('mb_contents').addClass('noscroll');
	$('mb_bottom').addClass('nodisplay');
	$('mb_overlay').addClass('nopointer');
};

/**
 * User initiated action to close modal_i box
 * @param string fn User defined callback function 
 */
function modal_iclose(fn) {
	closeable = true; 
	MOOdalBox.close();
	if(fn!==undefined) {
		eval(fn+"()"); 
	}
};
/**
 * Setup mouseovers 
 * @param string el - element id selector that contains img elements
 * @param string offAttr - img attribute that holds src of off-state
 * @param string onAttr - img attribute that holds src of on-state
 */
function hoverListener(el, offAttr, onAttr) {
	if (!document.getElementById) return;
	var imgOriginSrc;
	var imgTemp = new Array();
	var searchBlock = document.getElementById(el);
	var imgarr = searchBlock.getElementsByTagName('img');
	for (var i = 0; i < imgarr.length; i++) {
		if (imgarr[i].getAttribute(onAttr)) {
			imgTemp[i] = new Image();
			imgTemp[i].src = imgarr[i].getAttribute(onAttr);
			imgarr[i].onmouseover = function() {
				imgOriginSrc = this.getAttribute(offAttr);
				this.setAttribute(offAttr,this.getAttribute(onAttr));
			};
			imgarr[i].onmouseout = function() {
				if (imgOriginSrc) {
					this.setAttribute(offAttr,imgOriginSrc);
				}
			};
		}
	}
};

/**
 * Call this function if you would like to post to the ce_counter table with an activity id through javascript
 * Due to scope issues, no longer supports redir!
 * @example counterProxy({type:'presenter',aid:'181'});
 * @param {Object} obj
 */
function counterProxy(obj){
	obj.url = obj.url ? escape(obj.url) : null;
	var qstr = Object.toQueryString(obj); 
	var ajx = new Ajax(uri+'index.php?counter=true&tpl=counter&'+qstr,{method:'get',evalScripts:'true'}).request();	
}
	
/**
 *
 */
window.addEvent('domready',function() {
	/**
	 * Initialize moodalbox
	 */
	try { MOOdalBox.init(); } catch(e) {}

	indicate(0);

	/**
	 * "user activity collection" object
	 */
	var collector = new ActivityCollector('a.save', {
			duration: 200,
			placement: 'top',
			/*onLoad: function() { $('usr-total').setText(this.collection.length); },*/
			onComplete: function() { $('usr-total').setText(this.collection.length); },
			off: {
				className: 'off',
				text: '',
				icon: uri+'img/icon_saved.gif'
			},
			on: {
				className: 'clicked',
				text: '',
				icon: uri+'img/icon_save.gif'
			}
		}); 
		$('usr-total').setText(collector.collection().length);
    }); 

/**
 *
 * Set active anchor in static content areas
 *
 */
function setActiveAnchorSC(el){
    var ajaxs = $$('a.ajxLinks');
    if(typeof(el) != 'object'){
        var el = $(ajaxs[parseInt(el)].getProperty('id'));
    }
    if(el != false){
        ajaxs.each(function(off){
            var offParent = off.getParent();
            offParent.removeClass('active');
        });
        var elParent = el.getParent();
        elParent.addClass('active');
    }
}


/*
 *
 * Create outbound link click event for google analytics
 *
 */
function gaOutboundLinkEvent(link) {
    link.addEvent('click', function(ev){
        var ev = new Event(ev);
        ev.preventDefault();
        gaOutboundLinkRecord(link, 'Outbound Links', link.getProperty('title'));
        return false;
    });
}

/*
 *
 * Track outbound links for google analytics
 *
 */
function gaOutboundLinkRecord(link, category, action) {
    try {
        // ZLS 2011-02-09: This is pasted from google page, but params in request fired don't include category or action anywhere. This is probably incorrect and should be removed once Events appear in analytics.
        //_gaq.push(['pageTracker._trackEvent', category, action ]);

        pageTracker._trackEvent(category, action);
        setTimeout('document.location = "' + link.href + '"', 750);

    }catch(err){}
}

