rS = {
	loggedIn: false,
	fbStream: false,
	fbInviteBox: {
		method: 'fbml.dialog',
		fbml: '<fb:request-form action="'+location.href+'" method="POST" invite="true" type="This" content="Event Invitaton"><fb:multi-friend-selector condensed="true" showborder="true" email_invite="true" rows=3 cols=3 actiontext="Invite Your Friends"/><fb:request-form-submit /></fb:request-form>',
		width: 700,
		height: 540,
		display: 'iframe'
	},
	fbShareBox: {
		method: 'stream.share',
		u: location.href,
		display: 'iframe'
	},
	fbPublishBox: {
		method: 'stream.publish',
		message: 'A Ray Sweeten Activity',
		attachment: {
			name: 'Ray Sweeten',
			caption: 'Check this out',
			description: (
				'Description'
			),
			href: 'http://raysweeten.com/events'
		},
		action_links: [ {text: 'Permalink', href: 'http://raysweeten.com/events'}],
		user_message_prompt: 'Share your thoughts.',
		display: 'iframe'
	},
	oEmbedUrl: 'http://vimeo.com/api/oembed.json',
	wmode: 'transparent',
	vidWidth: 715,
	vidHeight: 444,
	vidTitle: '0',
	vidByline: '0',
	emailRegEx: /[^\s]+@[^\s]+([.]\w{2,3})+/,
	ccRegex: /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,
	dialogOpts: {bgiframe: true, autoOpen: false, modal: true, resizable: false, draggable: false, closeOnEscape: true, w: 306},
	
	validMail: function(p){
		var isValid = true;
		aV.resetForm();
		
		isValid = isValid && aV.checkLength(aVF.contactForm.name,'Name',1,15);
		isValid = isValid && aV.checkRegex(aVF.contactForm.email, /[^\s]+@[^\s]+([.]\w{2,3})+/, 'Please provide a valid email. e.g. user@gmail.com');
		isValid = isValid && aV.checkLength(aVF.contactForm.subject,'Subject',1,15);
		isValid = isValid && aV.checkLength(aVF.contactForm.message,'Message',1,2000);
		
		if(isValid){
			rS.action('/php/ajax/contactMe.php', 'post', {'name': aVF.contactForm.name.val(), 'email': aVF.contactForm.email.val(), 'subject' : aVF.contactForm.subject.val(), 'message': aVF.contactForm.message.val()}, '', rS.contactBefore, rS.contactComplete);
		}
	},
	
	contactBefore: function(data){
		
	},
	
	contactComplete: function(data){
		$('#contactPop .errorHolder').html('');
		
		var res = JSON.parse(data.responseText);
		if(res.error){
			alert(res.error);
		}else{
			$('#contactForm .userN').text(res.res);
			$('#contactPop').parent('.ui-dialog').find('.ui-dialog-buttonpane').fadeOut(200);
			$('#contactPop .formHold').fadeOut(200, function(){
				$('#contactPop .successHold').fadeIn(200);
			});
		}

	},
	
	validSubscribe: function(p){
		var isValid = true;
		aV.resetForm();
		
		isValid = isValid && aV.checkLength(aVF.subscribeForm.firstname,'Name',1,15);
		isValid = isValid && aV.checkLength(aVF.subscribeForm.lastname,'Name',1,15);
		isValid = isValid && aV.checkRegex(aVF.subscribeForm.email, /[^\s]+@[^\s]+([.]\w{2,3})+/, 'Please provide a valid email. e.g. user@gmail.com');
		
		if(isValid){
			rS.action('/php/ajax/subscribe.php', 'post', {'firstname': aVF.subscribeForm.firstname.val(), 'lastname': aVF.subscribeForm.lastname.val(), 'email': aVF.subscribeForm.email.val()}, '', rS.subscribeBefore, rS.subscribeComplete);
		}
	},
	
	subscribeBefore: function(data){
		
	},
	
	subscribeComplete: function(data){
		$('#subscribePop .errorHolder').html('');
		
		var res = JSON.parse(data.responseText);
		if(res.error){
			$('#subscribePop .errorHolder').text(res.error).show();
		}else{
			$('#subscribeForm .userN').text(res.res);
			$('#subscribePop').parent('.ui-dialog').find('.ui-dialog-buttonpane').fadeOut(200);
			$('#subscribePop .formHold').fadeOut(200, function(){
				$('#subscribePop .successHold').fadeIn(200);
			});
		}
	},
	
	init: $(document).ready(function(){
		
		/*FB.Event.subscribe('auth.sessionChange', function(res){
			if(res.session){
				
			}else{
				
			}
			window.location.reload();
		});
		
		FB.Event.subscribe('auth.login', function(response) {
			window.location.reload();
	    });*/

		$('#fbLogin').click( function(e){
			FB.login( function(res){
				if(res.session){
					if(res.perms){
						
					}
					window.location.reload();
				}
			},
			{perms: 'publish_stream'}
			);
			e.preventDefault();
		});
		
		$('#fbInvite').click( function(e){
			FB.ui(rS.fbInviteBox, function(res){
				
			});
			e.preventDefault();
		});
		$('#fbShare').click( function(e){
			FB.ui(rS.fbShareBox, function(res){
				
			});
			e.preventDefault();
		});
		
		$('#fbPublish').click( function(e){
			FB.ui(rS.fbPublishBox, function(res){
				
			});
			e.preventDefault();
		});
		
		$('#fbLogout').click( function(e){
			FB.logout( function(res){
				window.location.reload();
			});
			e.preventDefault();
		});
		
		$('a.prev, a.next').click(rS.getMonth);
		
		$('.evEnt').slideDown(600, function(){
			if($('.locate').length){
				rGM.initialize('map');
				//rGM.address = $('.locate').text();
				//rGM.showAddress(rGM.address); 
			}
		});
		
		$('.eList a:odd').addClass('alt');
		
		//if($('#map').length) rGM.initialize('map');
		if($('#byteMap').length) rGM.initialize('byteMap');
		
		$('#hifi .cpTop a').each( function(i,e){
			var _this = $(this);
			// preload thumbnails
			var _img = new Image;
			_img.src = _this.attr('data-thumb');
			
			_this.hover( function(e){
				$('.cpTop .title').text(_this.text());
				$('.cpTop .desc').html(_this.attr('data-description'));
				$('.cpTop .views').text(_this.attr('data-plays'));
				$('.cpTop .date').text(_this.attr('data-uploaded'));
				$('.cpTop .hoverBar').prepend(_img);
				$('#hifi .cpTop .hoverBar').show();
			}, function(e){
				$('#hifi .cpTop .hoverBar').hide();
				$('.cpTop .hoverBar img').remove();
			});
		});
		
		if(mIsSet){
			// mIsSet has been set in the header. We'll use the value of mIsSet 
			// to find the correct video ID
			rS.vidID = $("#"+mIsSet).attr('data-vidID');
			rS.oEmbed();
		}
		
		$('.eList .accordion').accordion({header: '.aH', collapsible: true, autoHeight: false, active: false});
		$('.eList a').click( function(e){
			var y = $(this).attr('href');
			var year = y.split('/')[4];
			$.cookies.set('current_evt_blind', year);
		});
		
		$('.blockHead h3 a').click( function(){ $.cookies.del('current_evt_blind'); });
		
		if($.cookies.get('current_evt_blind')){
			var l = $.cookies.get('current_evt_blind');
			$('.aH:contains('+l+')').click();
		}
		
		$('#contactPop').dialog({
			bgiframe: rS.dialogOpts.bgiframe,
			autoOpen: rS.dialogOpts.autoOpen,
			modal: rS.dialogOpts.modal,
			resizable: rS.dialogOpts.resizable,
			draggable: rS.dialogOpts.draggable,
			closeOnEscape: rS.dialogOpts.closeOnEscape,
			width: 500,
			buttons: {
				'Send Email': function(){
					rS.validMail($(this));
				},
				Cancel: function(){
					$(this).dialog('close');
				}
			},
			
			close: function(){
				aV.resetForm(aVF.contactForm);
				$('#contactPop .formHold').show();
				$('#contactPop').parent('.ui-dialog').find('.ui-dialog-buttonpane').show();
				$('#contactPop .successHold').hide();
			}
		});
		
		$('#subscribePop').dialog({
			bgiframe: rS.dialogOpts.bgiframe,
			autoOpen: rS.dialogOpts.autoOpen,
			modal: rS.dialogOpts.modal,
			resizable: rS.dialogOpts.resizable,
			draggable: rS.dialogOpts.draggable,
			closeOnEscape: rS.dialogOpts.closeOnEscape,
			width: 350,
			buttons: {
				'Subscribe': function(){
					rS.validSubscribe($(this));
				},
				Cancel: function(){
					$(this).dialog('close');
				}
			},
			
			close: function(){
				aV.resetForm(aVF.subscribeForm);
				$('#subscribePop .formHold').show();
				$('#subscribePop').parent('.ui-dialog').find('.ui-dialog-buttonpane').show();
				$('#subscribePop .successHold').hide();
			}
		});
		
		$('.subscribeLink').click( function(e){
			$('#subscribePop').dialog('open');
			e.preventDefault();
		});
		
		$('.contactLink').click( function(e){
			$('#contactPop').dialog('open');
			e.preventDefault();
		});
	}),
	getMonth: function(e){
		var m = $(this).attr('data-month');
		var y = $(this).attr('name');
		rS.action('/php/ajax/getCalJson.php', 'get', {'m':m,'y':y}, null, rS.calWaiter, rS.updateCal);
		e.preventDefault();
	},
	updateCal: function(data){
		var item = eval('(' + data.responseText + ')');
		$('a.prev').attr('name',item.prevY).attr('data-month',item.prevM).attr('href','/events/'+item.prevM+'/');
		$('a.next').attr('name',item.nextY).attr('data-month',item.nextM).attr('href','/events/'+item.nextM+'/');
		$('.month').text(item.month+' '+item.year);
		$('.calDays').empty().html('<tr>'+item.html);
		$('.cal .waiter').fadeOut(100);

	},
	action: function(path, type, param, dataTypeReturned, beforeSend, onComplete){
		if(!beforeSend) beforeSend = '';
		if(!onComplete) onComplete = '';
		if(!type) type = 'post';
		if(!dataTypeReturned) dataTypeReturned = 'json';
		$.ajax({
			url: path,
			type: type,
			data: param,
			dataType: dataTypeReturned,
			beforeSend: beforeSend,
			success: '',
			complete: onComplete
		});
	},
	loadScript: function(url){
		var js = document.createElement('script');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', url);
		document.getElementsByTagName('head').item(0).appendChild(js);
	},
	oEmbed: function(){
		//alert(rS.oEmbedUrl + '?url=' + encodeURIComponent('http://vimeo.com/'+rS.vidID) + '&wmode='+rS.wmode+'&width='+rS.vidWidth+'&height='+rS.vidHeight+'&callback=rS.oEmbedCallback');
		rS.loadScript(rS.oEmbedUrl + '?url=' + encodeURIComponent('http://vimeo.com/'+rS.vidID) + '&width='+rS.vidWidth+'&height='+rS.vidHeight+'&title='+rS.vidTitle+'&byline='+rS.vidByline+'&callback=rS.oEmbedCallback');
	},
	oEmbedCallback: function(video){
		//alert(unescape(video.html));
		document.getElementById('myContent').innerHTML = unescape(video.html);
	},
	unix_tstamp: function(){
		return parseInt(new Date().getTime().toString().substring(0, 10));
	},
	calWaiter: function(){
		$('.cal .waiter').fadeIn(100);
	},
	encHTML: function(string){
		return string.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
	}
}

rGM = {
	geo: null,
	map: null,
	byteMap: null,
	marker: null,
	address: null,
	latlng: null,
	place: null,
	staticZoom: 16,
	
	addyArray: new Array(),
    LLarray: new Array(),
	pkArray: new Array(),
	titles: new Array(),
	postDates: new Array(),
	markers: new Array(),
	current: new Array(),
	pinpoint: false,

	clusterOpts: {gridSize: 50, maxZoom: 15},
	clusterStyleOpts: {url: '/assets/img/clusters/'},
	cluster: null,
	
	// Call this function when the page has been loaded
	initialize: function(id) {
		rGM.geo = new GClientGeocoder();
	  
		var map = $('#'+id);
		map.empty().show();
		rGM.map = new GMap2(document.getElementById(id));
		rGM.map.addControl(new GMapTypeControl());
		rGM.map.enableContinuousZoom();
		rGM.map.enableScrollWheelZoom();
		//rGM.map.addMapType(G_SATELLITE_3D_MAP);
		//rGM.map.addMapType(G_MARS_INFRARED_MAP );
		rGM.map.setMapType(G_SATELLITE_MAP);
		//rGM.map.setUIToDefault();
		//rGM.map.enableRotation();
	  //build address and lat/long array
	  $('.locate').each( function(i,e){
	  		var ind = i;
	  		rGM.addyArray[i] = $(this).attr('addr');
			rGM.pkArray[i] = $(this).attr('name');
			rGM.titles[i] = $(this).text();
			rGM.postDates[i] = $(this).attr('rel');
			rGM.current[i] = $(this).hasClass('current');
			
			var pk = $(this).attr('href');
			var title = $(this).text();
			var date = $(this).attr('rel');
			rGM.geo.getLatLng($(this).attr('addr'), function(point) {
            	rGM.LLarray[i] = point;
				if(!rGM.bounds){
					rGM.bounds = new GLatLngBounds(point);
				}
				rGM.buildMarks(i);
            });
	  });
	},
	buildMarks: function(i){
		var index = parseInt(i + 1, 10);
		rGM.geo.getLatLng(rGM.addyArray[i], function(point) {
			
			rGM.multiPoint(rGM.LLarray[i], i);
			
			//We check to make sure all markers have been built
			// by comparing rGM.markers and $('.locate) lengths
			// If they are equal, run rGM.cluster
			if(rGM.markers.length == $('.locate').length){
				rGM.cluster();
			}
		});
	},
	cluster: function(){
		rGM.cluster = new MarkerClusterer(rGM.map, rGM.markers, {styles: styles[0]});
	},
	setBounds: function(addr) {
        //New Map Bounds instance stored in rGM.bounds
        //This is only used for maps with multiple points
        rGM.geo.getLatLng(rGM.addyArray[0], function(point) {
            rGM.bounds = new GLatLngBounds(point);
        });
    },

	/**
	 * 
	 * @param {Object} point
	 * @param {Object} i
	 * 
	 * for any map / makes sure that map bounds are set correctly
	 * 
	 * When there are multiple points, it expands the map bounds according to the
	 * points.
	 * 
	 * When there is only one point it sets the center to the point and sets to
	 * a static zoom level set above in rGM.staticZoom.
	 * 
	 * For each point, multiPoint runs rGM.makeMarker
	 */
    multiPoint: function(point, i) {
        var box = rGM.bounds;
		//Extend the box
        box.extend(point);
		
		if(rGM.current[i] && rGM.pkArray.length > 1){
			rGM.map.setCenter(point, 19);
			rGM.pinpoint = true;
		}
		if(!rGM.pinpoint){
			//Zoom the map to show all the markers
        	rGM.map.setCenter(box.getCenter(), rGM.map.getBoundsZoomLevel(box) - 0);
		}
		if(rGM.pkArray.length == 1){
			//Zoom the map to show all the markers
        	rGM.map.setCenter(box.getCenter(), rGM.staticZoom);
		}
		
		rGM.makeMarker(point, i);
    },
	
	/**
	 * 
	 * @param {Object} point
	 * @param {Object} i
	 * 
	 * Make the markers, but only add them to the rGM.markers array.
	 * MarkerClusterer will deal with rendering them to the map from the rGM.markers array.
	 */
    makeMarker: function(point, i) {
		if(rGM.addyArray.length > 1){
			rGM.audioIcon();
		}else{
			rGM.baseIcon();
		}
		
		
		if(rGM.current[i]){
			rGM.iconEar.image = "/assets/img/markers/audioCurrentTape.png";
		}

        // Set up our GMarkerOptions object
        markerOptions = { icon: rGM.iconEar, title: rGM.titles[i] };
        var marker = new GMarker(point, markerOptions);
		
		// Add click event if there are more than one markers (for sound map)
		if(rGM.pkArray.length > 1){
			GEvent.addListener(marker, "mouseover", function(ll){
				marker.openInfoWindowHtml('<p class="title"><strong>'+rGM.titles[i]+'</strong></p><p><strong>posted: </strong>'+rGM.postDates[i]+'</p>');
			});
			
			GEvent.addListener(marker, "mouseout", function(ll){
				rGM.map.closeInfoWindow();
			});
			
			GEvent.addListener(marker, "click", function(ll){
				location = '/maps/'+rGM.pkArray[i]+'/';
			});
		}
		
		rGM.markers[i] = marker;
        //return marker;
    },
	showAddress: function(v){
		$('#map').empty().show();
		rGM.map = new google.maps.Map2(document.getElementById("map"));
		rGM.map.addControl(new GMapTypeControl());
		rGM.map.enableContinuousZoom();
		rGM.map.enableScrollWheelZoom();
		rGM.map.setMapType(G_SATELLITE_MAP);
		if(rGM.geo) {
			rGM.geo.getLatLng(
				v,
				function(point){
					if(!point){
						alert(v+' was not found.');
					}else{
						rGM.latlng = point;
						rGM.geo.getLocations(point, rGM.getPlace);
						
						rGM.map.setCenter(point, 13);
						rGM.marker = new GMarker(point, {draggable: true});
						
						rGM.makeMark();
						rGM.map.addOverlay(rGM.marker);
						/*GM.marker.openInfoWindowHtml(
							'<b>'+v+'</b><br />'
							//'<b>LatLng:</b> '+ GM.place.x +',' +GM.place.y+'<br />' 
						);*/
					}
				}
			);
		}
	},
	getPlace: function(res){
		//GM.map.clearOverlays();
		if(!res || res.Status.code != 200){
			//alert('Status code: '+ res.Status.code);
		}else{
			place = res.Placemark[0];
			rGM.place = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			
			/*GM.marker.openInfoWindowHtml(
				'<b>orig latlng:</b>' + res.name + '<br/>' +
				'<b>latlng:</b>' + place.Point.coordinates[0] + "," + place.Point.coordinates[1] + '<br>' +
				//'<b>Status Code:</b>' + res.Status.code + '<br>' +
				//'<b>Status Request:</b>' + res.Status.request + '<br>' +
				'<b>Address:</b>' + place.address + '<br>' +
				'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
				'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);*/
		}
	},
	getAddress: function(ll){
		if(ll != null){
			rGM.address = ll;
			rGM.geo.getLocations(ll, rGM.showAddress2);
		}
	},
	makeMark: function(point){

	  GEvent.addListener(rGM.marker, "dragstart", function() {
		rGM.map.closeInfoWindow();
	  });

	  GEvent.addListener(rGM.marker, "dragend", rGM.getAddress);
	},
	baseIcon: function() {
        //Create a base Icon for numbered markers
        rGM.baseIcon = new GIcon(G_DEFAULT_ICON);
        rGM.baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        rGM.baseIcon.iconSize = new GSize(26, 39);
        rGM.baseIcon.shadowSize = new GSize(37, 42);
        rGM.baseIcon.iconAnchor = new GPoint(9, 34);
        rGM.baseIcon.infoWindowAnchor = new GPoint(9, 2);
    },
    audioIcon: function() {
        //Create a base Icon for Audio markers
		rGM.iconEar = new GIcon(G_DEFAULT_ICON);
       rGM.iconEar.image = "/assets/img/markers/audioTape.png";
	   rGM.iconEar.iconSize = new GSize(30, 37);
	   rGM.iconEar.shadowSize = new GSize(37, 36);
	   rGM.iconEar.iconAnchor = new GPoint(12, 34);
	   rGM.iconEar.imageMap = [0,0,30,0,30,37,0,37,0,0];
    }
}

jQuery.fn.encHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'));
  });
};
 
jQuery.fn.decHTML = function() {
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
};
 
jQuery.fn.isEncHTML = function(str) {
  if(str.search(/&amp;/g) != -1 || str.search(/&lt;/g) != -1 || str.search(/&gt;/g) != -1)
    return true;
  else
    return false;
};
 
jQuery.fn.decHTMLifEnc = function(){
  return this.each(function(){
    var me   = jQuery(this);
    var html = me.html();
    if(jQuery.fn.isEncHTML(html))
      me.html(html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
  });
}
