var selected_group = false;
var display_width = 820;
var content_width = 0;

var groups_data;
var last_group = 0;
var noMoreGroups = false;

var scroll_position = 0;
var scroll_amount = 500;

var atEnd = false;// TEMP TODO NEW LMAO BUTTES

var m = new Element('featureDetect');
m.style.cssText = "-webkit-animation: 'animate' 2s ease 2;";
var hasAnimation = m.style['webkitAnimationName'];

document.addEvent('domready',function() {
	initEditEvents();
	display_width = $('alsoBy').clientWidth;

	var loadreq = new Request({
				'url': '/js?tuserid='+tuser.tuserid+"&plzinclude="+current_shorturl,
				'method': 'get'
				});
	
	loadreq.addEvent('success', function(responseText) {
			$('moveLeft').addClass('disabled');
			$('moveLeft').addEvent('click', function() {
				scrollToLeft();
				return false;
			});
			$('moveRight').addEvent('click', function() {
				scrollToRight();
				return false;
			});
			
			groups_data = JSON.decode(responseText);
			showMoreThumbs();
	
			//scroll until the current page (1) exists (2) is visible
			while (!$('group_'+current_shorturl) || (!farRight && $('group_'+current_shorturl).offsetLeft > scroll_position+scroll_amount)) {
				scrollToRight();
			}
			
			selected_group = $('group_'+current_shorturl);
			updateArrowButtons();
			updateGroupArrowPosition();
		});
	
	loadreq.send();
});


function showMoreThumbs() {
	var groups_elem = $('alsoByGroups');
	for(;last_group<groups_data.length;) {
		group = groups_data[last_group];

		var group_elem = document.createElement('a');
		group_elem.className = 'group '+(group.shorturl==current_shorturl?'selected ':' ')+(group.thumbs.length>1?'multi':'single');
		group_elem.href = '/'+group.shorturl;
		group_elem.id = 'group_'+group.shorturl;
		group_elem.shortcode = group.shorturl;

		if (group.shorturl==current_shorturl)
			selected_group = group_elem;
		
		var isFirst = true;
		group.thumbs.each(function(thumb) {
			var thumb_div = document.createElement('div');
			thumb_div.className='thumb';
			thumb_div.group = group_elem;
			thumb_div.pictureid = thumb.pictureid;
			thumb_div.isFirst = isFirst; isFirst = false;
			var img = document.createElement('img');
			img.src = thumb.url;
			img.width = thumb.width;
			img.height = thumb.height;
			if (group.thumbs.length==1)
				img.style.marginTop = (120 - thumb.height) / 2 + 'px';
			thumb_div.appendChild(img);
			group_elem.appendChild(thumb_div);
						
			thumb_div.addEvent('click', function(evt) {
				clickthumb = evt.target;
				while (!clickthumb.hasClass('thumb'))
					clickthumb = clickthumb.parentNode;
				clickgroup = clickthumb.group;
				
				if (clickgroup.shortcode==current_shorturl) {
					if (clickthumb.isFirst)
						var myFx = new Fx.Scroll(window,{offset:{'x':0,'y':-25}}).toElement('contentArea');
					else
						var myFx = new Fx.Scroll(window,{offset:{'x':0,'y':-25}}).toElement('photo'+clickthumb.pictureid);
					return false;
				}
				
				goToPage(clickgroup,clickthumb.isFirst?'first':clickthumb.pictureid);
				return false;
			});
		});
		
		var groupdate_elem = document.createElement('div');
		groupdate_elem.className='groupDate';
		groupdate_elem.innerHTML = group.date;
		group_elem.appendChild(groupdate_elem);
		
//		var grouparrow_elem = document.createElement('div');
//		grouparrow_elem.className='groupArrow';
//		group_elem.appendChild(grouparrow_elem);
		
		var groupcount_elem = document.createElement('div');
		groupcount_elem.className='groupCount n'+group.thumbs.length;
		groupcount_elem.innerHTML = group.thumbs.length;
		group_elem.appendChild(groupcount_elem);
		
		groups_elem.appendChild(group_elem);
		groups_data[last_group].group_elem = group_elem;
		groups_data[last_group].leftPos = group_elem.offsetLeft;
		groups_data[last_group].rightPos = group_elem.offsetLeft+group_elem.offsetWidth;
		content_width = Math.max(content_width,groups_data[last_group].rightPos);
		
		last_group++; //increase it even if we break
		if (content_width> (scroll_position+display_width) ) //TODO move this to the for
			break;
	};
	
	noMoreGroups = last_group == groups_data.length;
}

function goToPage(group_elem,scrollToId) {
	var contentArea_req = new Request({
		'url': '/'+group_elem.shortcode+'/contentArea',
//		'url': 'http://campl.us/'+group_elem.shortcode+'/contentArea',
		'method': 'get'
	});
	
	//otherwise mootools will strip our geocoding function
	contentArea_req.processScripts = function(text){
		return text;
	};
	
	contentArea_req.addEvent('success',function(responseText) {
		fromBottom = document.height-window.scrollY;
		
		if (selected_group)
			selected_group.removeClass('selected');
		selected_group = group_elem;
		selected_group.addClass('selected');
		current_shorturl = group_elem.shortcode;
		
		var x = updateGroupArrowPosition();
		if (x-scroll_position<20)
			scrollToLeft();
		if (x-scroll_position>780)
			scrollToRight();
		
		$('contentArea').innerHTML = responseText;
		$('contentArea').getElements('script').each(function(item) {
			eval(item.innerHTML);
		});
		
		socialcomments[0].config['container_elem'] = $('commenting_container');
		socialcomments[0].config['ajax_url'] = '/'+current_shorturl+'/commentArea?';
		socialcomments[0].initEvents();
		
		initEditEvents();
		
		window.scroll(0,document.height-fromBottom);
		if (scrollToId=='first') {
			setTimeout(function() {
				var myFx = new Fx.Scroll(window,{offset:{'x':0,'y':-25}}).toElement('contentArea');
			},500);
		} else {
			setTimeout(function() {
				var myFx = new Fx.Scroll(window,{offset:{'x':0,'y':-25}}).toElement('photo'+scrollToId);
			},500);
		}

		ajaxtrack('http://campl.us/'+current_shorturl);
	});
	
	if ('pushState' in window.history)
		window.history.pushState({'shortcode':group_elem.shortcode, 'scrollToId':scrollToId, 'fromBottom':(document.height-window.scrollY)}, "Campl.us: "+group_elem.shortcode, '/'+group_elem.shortcode);
	else
		document.location.href = '#'+group_elem.shortcode;
	
	contentArea_req.send();
}


window.onpopstate = function(e) {
	if (e.state==null) {
//		console.log('e.state==null');
		if (current_shorturl!=start_shorturl)
			goToPage($('group_'+start_shorturl),'first');
			
	} else if ($('group_'+e.state.shortcode)) {
//		console.log('shortcode');
//		window.scroll(0,document.height-e.state.fromBottom);
		goToPage($('group_'+e.state.shortcode),e.state.scrollToId);
		
	} else if ($('group_'+e.state.group_elem)) {
//		console.log('group_elem');
//		window.scroll(0,document.height-e.state.fromBottom);
		goToPage($('group_'+e.state.group_elem),e.state.scrollToId);
	}
};

var scrollFx;

function elasticBounce(x1,x2) {

		$('alsoByGroups').addClass('elastic');
		
		if (hasAnimation)
			$('alsoByGroups').style.left = x1+"px";
		else
			$('alsoByGroups').tween('left',x1);
		
		setTimeout(function() {
			if (hasAnimation)
				$('alsoByGroups').style.left = x2+"px";
			else
				$('alsoByGroups').tween('left',x2);		
		},300);
		
		setTimeout(function() {
			$('alsoByGroups').removeClass('elastic');
		},600);
		return;
}

function scrollBrowserTo(x) {
	if (hasAnimation)
		$('alsoByGroups').style.left = x+"px";
	else
		$('alsoByGroups').tween('left',x);
}

function updateArrowButtons() {
	farRight = noMoreGroups && content_width < scroll_position+display_width;

	$('moveLeft').removeClass('disabled');
	$('moveRight').removeClass('disabled');
	
	if (scroll_position==0)
		$('moveLeft').addClass('disabled');
		
	if (farRight)
		$('moveRight').addClass('disabled');
}

function updateGroupArrowPosition() {
	var leftmost = Math.max(scroll_position,selected_group.offsetLeft);
	var rightmost = Math.min(scroll_position+display_width,selected_group.offsetLeft+selected_group.offsetWidth);
	var x = ((leftmost+(rightmost-leftmost)/2)-$("groupArrow").offsetWidth/2);
	
	if (hasAnimation)
		$('groupArrow').style.left = x+"px";
	else
		$('groupArrow').tween('left',x);
	
	return x;
}

function scrollToLeft() {
	if (scroll_position<=0) {
		elasticBounce(30,0);
		return;
	}
	
	scroll_position -= scroll_amount;
	scroll_position = Math.max(scroll_position,0);

	updateArrowButtons();
	updateGroupArrowPosition();
	
	scrollBrowserTo(-scroll_position);
}

var farRight = false;
function scrollToRight() {
	if (farRight) {
		elasticBounce(-scroll_position-30,-scroll_position);
		return;
	}
	
	scroll_position += scroll_amount;
	showMoreThumbs();
	
	updateArrowButtons();
	updateGroupArrowPosition();
	
	scrollBrowserTo(-scroll_position)
}

var geocoder;
var map;

function check_map(items) {
	if (!items.length) {
		$('tweetLocationStuff').style.display = 'none';
	}
}

// Call this function when the page has been loaded
function initialize_map(items) {
	if (map) //already inited
		return;
	
	if (!items.length) {
		$('tweetLocationStuff').style.display = 'none';
		return;
	}
	$('tweetLocationStuff').style.display = 'inline';
  
  var mapDiv = document.getElementById("mapElement");
  geocoder = new google.maps.Geocoder();

  var latlng = new google.maps.LatLng(items[0].lat,items[0].lon);
  var myOptions = {
    zoom: 20,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(mapDiv, myOptions);
  map.setZoom(11);
  
  //add pins for each image
  var positions = new Array();
  var existing = new Array();
  items.each(function(item) {
  	if (!existing[item.lat+','+item.lon]) {//we're using mootools foreach so no continue
  		existing[item.lat+','+item.lon] = true;
  	
  		var p = new google.maps.LatLng(item.lat,item.lon);
  		positions.push(p);
  		marker = new google.maps.Marker({
  			position: p, 
  			map: map,
  			icon: item.img
  		});
  	}
  });
  
  //automatic zoom to fit
  if (positions.length>1) {
  	var bounds = new google.maps.LatLngBounds ();
  	for (var i = 0, LtLgLen = positions.length; i < LtLgLen; i++) {
  	  bounds.extend (positions[i]);
  	}
  	map.fitBounds (bounds);
  }

  // map.addOverlay(new GMarker(latlng));
  
  if (!$('mapPlaceName').hasClass('isCoded') && geocoder) {
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK && results[3]) {
  		$('mapPlaceName').innerHTML = results[3].formatted_address;
      }
    });
  }
  
  ajaxtrack('http://campl.us/mapinit');
}

function ajaxtrack(url) {
	if (reinvigorate) {
		reinvigorate.ajax_track(url);
	}
}

//	window.onload = function() { initialize(); }






/**
	config:
		- className
		- text
		- buttons[]
			- text
			- name
			- onclick
		- form
			- action
			- submitText
			- cancelText
			- optionName
			- optionText
			- optionSelected

*/
function PopupDialog(name,config) {
	var dialog = this;
	this.element = false;
	this.name = name;
	this.config = config;
	this.configurables = {};

	this.show = function(reconfig) {
		if (!dialog.element)
			dialog.prepare();
		
		if (reconfig != undefined) {
			if (reconfig['optionText']!=undefined)
				dialog.configurables['opt_label'].innerHTML = reconfig['optionText'];
				
			if (reconfig['optionVisible']!=undefined) {
				if (reconfig['optionVisible']) {
					dialog.configurables['opt_check'].type = 'checkbox';
					dialog.configurables['opt_check'].value = 'y';
					dialog.configurables['opt_label'].style.display = 'inline';
				} else {
					dialog.configurables['opt_check'].type = 'hidden';
					dialog.configurables['opt_check'].value = reconfig['optionSelected']?'y':'';
					dialog.configurables['opt_label'].style.display = 'none';
				}
			}

			if (reconfig['optionSelected']!=undefined) {
				dialog.configurables['opt_check'].checked = reconfig['optionSelected'];
			}
			
			if (reconfig['htmlArea']!=undefined) {
				dialog.configurables['htmlArea'].innerHTML = reconfig['htmlArea'];
			}
		}
		
		$('cover').addClass('show');
		$(dialog.element).addClass('show');
	};
	
	this.hide = function() {
		$('cover').removeClass('show');
		dialog.element.removeClass('show');
	};
	
	this.prepare = function() {
		var el = document.createElement('div');
		el.id = 'popdialog_'+dialog.name;
		el.className = 'popdialog '+(dialog.config['className']!=undefined?dialog.config['className']:'');
		
		var p = document.createElement('p');
		p.innerHTML = dialog.config['text'];
		el.appendChild(p);
		
		if (dialog.config['htmlArea'] != undefined) {
			var area = document.createElement('div');
			area.className='htmlArea';
			area.innerHTML = dialog.config['htmlArea'];
			dialog.configurables['htmlArea'] = area;
		}

		
		if (dialog.config['form'] != undefined) {
			var form = document.createElement('form');
			form.method = 'POST';
			
			if (dialog.config['htmlArea'] != undefined)
				form.appendChild(area);
			
			var action = document.createElement('input');
			action.type = 'hidden';
			action.name = 'action';
			action.value = dialog.config['form']['action'];
			form.appendChild(action);

			if (dialog.config['form']['optionName'] != undefined) {
				var opt = document.createElement('input');
				opt.type = 'checkbox';
				opt.name = dialog.config['form']['optionName'];
				opt.id = 'popdialog_'+dialog.name+'_option_'+dialog.config['form']['optionName'];
				opt.value = 'y';
				opt.checked = dialog.config['form']['optionSelected'];
				dialog.configurables['opt_check'] = opt;
				form.appendChild(opt);
				
				var label = document.createElement('label');
				label.innerHTML = dialog.config['form']['optionText'];
				label.htmlFor = opt.id;
				dialog.configurables['opt_label'] = label;
				form.appendChild(label);
			}
			
			var btns = document.createElement('div');
			btns.className = 'buttons';
			
			var submit = document.createElement('input');
			submit.type = 'submit';
			submit.name = 'submit';
			submit.value = dialog.config['form']['submitText'];
			submit.className = 'button';
			btns.appendChild(submit);
		
			var btn = document.createElement('div');
			btn.innerHTML = dialog.config['form']['cancelText'];
			btn.className = 'button cancel';
			$(btn).addEvent('click', function() { dialog.hide(); return false; });
			btns.appendChild(btn);
			
			form.appendChild(btns);
			
			el.appendChild(form);
		} else {
			if (dialog.config['htmlArea'] != undefined)
				el.appendChild(area);
		}
		
		if (dialog.config['buttons'] != undefined) {
			var btns = document.createElement('div');
			btns.className = 'buttons';
			
			dialog.config['buttons'].each(function(item) {
				var btn = document.createElement('div');
				btn.innerHTML = item.text;
				btn.id = 'popdialog_'+dialog.name+'_button_'+item.name;
				btn.className = 'button '+item.name;
				btn.addEvent('click',item.onclick);
				btns.appendChild(btn);
			});
			
			el.appendChild(btns);
		}

		dialog.element = el;
		document.body.insertBefore(dialog.element, document.body.firstChild);
	};
}

var dialog_comments_hide = new PopupDialog('disablecomments', {
		'text': 'Are you sure you want to disable comments on this photo?',
		'className': 'withicon',
		'form': {
			'action': 'hide_comments',
			'submitText': 'Disable comments',
			'cancelText': 'Keep comments',
			'optionName': 'autohide_comments',
			'optionText': 'Always disable comments on future photos',
			'optionSelected': false
		}
	});
	
var dialog_comments_show = new PopupDialog('enablecomments', {
		'text': 'Are you sure you want to enable comments on this photo?',
		'className': 'withicon',
		'form': {
			'action': 'hide_comments',
			'submitText': 'Enable comments',
			'cancelText': 'Keep comments off',
			'optionName': 'autohide_comments',
			'optionText': 'Continue disabling comments on future photos',
			'optionSelected': false
		}
	});
	
var dialog_meta_hide = new PopupDialog('hidemeta', {
		'text': 'Are you sure you wish to hide the meta data for this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'hide_exif',
			'submitText': 'Yes',
			'cancelText': 'Cancel',
			'optionName': 'autohide_exif',
			'optionText': 'Always hide meta data for my future posts',
			'optionSelected': false
		}
	});
	
var dialog_meta_show = new PopupDialog('showmeta', {
		'text': 'Are you sure you wish to show the meta data for this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'hide_exif',
			'submitText': 'Yes',
			'cancelText': 'Cancel',
			'optionName': 'autohide_exif',
			'optionText': 'Continue automatically hiding meta data for future posts',
			'optionSelected': false
		}
	});
	
var dialog_loc_hide = new PopupDialog('hideloc', {
		'text': 'Are you sure you wish to hide the location information for this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'hide_loc',
			'submitText': 'Yes',
			'cancelText': 'Cancel',
			'optionName': 'autohide_loc',
			'optionText': 'Always hide location information for my future posts',
			'optionSelected': false
		}
	});
	
var dialog_loc_hide = new PopupDialog('hideloc', {
		'text': 'Are you sure you wish to hide the location information for this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'hide_loc',
			'submitText': 'Yes',
			'cancelText': 'Cancel',
			'optionName': 'autohide_loc',
			'optionText': 'Always hide location information for my future posts',
			'optionSelected': false
		}
	});
	
var dialog_loc_show = new PopupDialog('showloc', {
		'text': 'Are you sure you wish to show the location information for this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'hide_loc',
			'submitText': 'Yes',
			'cancelText': 'Cancel',
			'optionName': 'autohide_loc',
			'optionText': 'Continue automatically hiding location information for future posts',
			'optionSelected': false
		}
	});
	
var dialog_delete_single = new PopupDialog('deletesingle', {
		'text': 'Are you sure you wish to delete this photo?',
		'className': 'withicon',
		'form': {
			'action': 'delete_set',
			'submitText': 'Delete',
			'cancelText': 'Don\'t delete'
		}
	});
	
var dialog_delete_multi = new PopupDialog('deletemulti', {
		'text': 'Are you sure you wish to delete this photoset?',
		'className': 'withicon',
		'form': {
			'action': 'delete_set',
			'submitText': 'Delete',
			'cancelText': 'Don\'t delete'
		}
	});
	
var dialog_delete_specific = new PopupDialog('deletespecific', {
		'text': 'Are you sure you wish to delete this photo?',
		'className': 'withicon',
		'htmlArea': '',
		'form': {
			'action': 'delete_specific',
			'submitText': 'Delete',
			'cancelText': 'Don\'t delete',
		}
	});
	
function initEditEvents() {
	if (page.is_owner) {
		$('togcommentslink').addEvent('click',function() {
			if (page.hide_comments) {
				if (tuser.autohide_comments)
					dialog_comments_show.show({ 'optionSelected':tuser.autohide_comments, 'optionVisible':true });
				else
					dialog_comments_show.show({ 'optionSelected':tuser.autohide_comments, 'optionVisible':false });
				
			} else
				dialog_comments_hide.show({ 'optionSelected':tuser.autohide_comments });
			
			return false;
		});
		
		$('togexiflink').addEvent('click', function() {
			if (page.hide_exif) {
				if (tuser.autohide_exif)
					dialog_meta_show.show({ 'optionSelected':tuser.autohide_exif, 'optionVisible':true });
				else
					dialog_meta_show.show({ 'optionSelected':tuser.autohide_exif, 'optionVisible':false });
				
			} else
				dialog_meta_hide.show({ 'optionSelected':tuser.autohide_exif });
			
			return false;
		});
		
		if (page.has_loc) {
			$('togloclink').addEvent('click', function() {
				if (page.hide_loc) {
					if (tuser.autohide_loc)
						dialog_loc_show.show({ 'optionSelected':tuser.autohide_loc, 'optionVisible':true });
					else
						dialog_loc_show.show({ 'optionSelected':tuser.autohide_loc, 'optionVisible':false });
					
				} else
					dialog_loc_hide.show({ 'optionSelected':tuser.autohide_loc });
				
				return false;
				});
		}
		
		$('deletesetlink').addEvent('click', function() {
			if (page.cnt_pictures==1) {
				dialog_delete_single.show();
			} else {
				dialog_delete_multi.show();
			}
			return false;
		});
		
		if ($('deletesetlink2')) {
			$('deletesetlink2').addEvent('click', function() {
				dialog_delete_single.show();
				return false;
			});
		}
		
		$$('.singledel').each(function(elem) {
			elem.addEvent('click', function() {
				dialog_delete_specific.show({
					'htmlArea': '<img src="'+imgmeta[elem.id].thumburl+'" /> <input type="hidden" name="pictureid" value="'+imgmeta[elem.id].pictureid+'">'
				});
			});
		});

	}
}
