/**
// Copyright (C) 2009 - 2011 Mike Feng Jinglong
//
// This program is a commercial software; you cannot redistribute it
// and/or modify it without the explicit consent from the author.
//
// All title and copyright in and to the Product is owned by Mike Feng
// and is protected by international copyright laws and treaty provisions.
// Mike Feng retains all ownership rights in the Product.
// The copyright notice must be reproduced and included on any copy
// that is expressly permitted under this Agreement.
**/
window.addEvent("domready", function() {
	Paginate();
	Sexy = new SexyAlertBox({
		OverlayStyles: {
			'background-color': '#fff',
			'opacity': 0.1
		}
	});
	$$('input[id=skip-album]').addEvent('click', function() {
		var myFx = new Fx.Tween('unpublished-album-message');
		myFx.start('height', '0px');
	});
	$$('input[id=publish-album]').addEvent('click', function() {
		publishAlbum(this.get('name'));
	});
	if (typeof(skipTips) == 'undefined')
		initTips();
	//blink message
	if ($$('div.message').length) {
		var blinking = function() {
			$$('.message').getElement('span').fade('out');
			(function() {
				$$('.message').getElement('span').fade();
			}).delay(500);
		};
		blinking.periodical(4000, blinking);
	}
});

function initViewPhoto(id, pid, nid) {
	//init enlarge photo link
	$$('a[id=Enlarge]').addEvent('click', function(e) {
		e.stop();
		var caption = (this.get('title')) ? '<strong>' + this.get('title') + '</strong>' : ''
		Shadowbox.open({
			enableKeys:	false,
			options: 	{handleOversize:'drag'},
			player:     'img',
			title:      caption,
			content:    this.href
		});
	});
	//init next photo when clicking on photo
	$$('a[id=photo-container-anchor]').removeEvents('click');
	$$('a[id=photo-container-anchor]').addEvent("click", function(e) { e.stop() });
	$$('img[id=currentphoto]').removeEvents('click');
	$$('img[id=currentphoto]').addEvent("click", function(e) {
		e.stop();
		if (tagging) addTag(e.page.x, e.page.y, id);
		else if (!cropping && pid + nid > 0) gotoPhoto(nid, $$('div[id=photo-container]').getElement('a').get('href'));
	});
	//init prev/next links
	$$('a[id=prevphoto-link]').removeEvents('click');
	$$('a[id=prevphoto-link]').addEvent('click', function(e) {
		e.stop();
		if (cropping || tagging || $('detail_panel').hasClass('detail_panel_loading')) return;
		gotoPhoto(pid, this.get('href'));
	});
	$$('a[id=nextphoto-link]').removeEvents('click');
	$$('a[id=nextphoto-link]').addEvent('click', function(e) {
		e.stop();
		if (cropping || tagging || $('detail_panel').hasClass('detail_panel_loading')) return;
		gotoPhoto(nid, this.get('href'));
	});
	//init edit caption link
	$$('a[id=photo-caption-toggle]').addEvent('click', function(e) {
		e.stop();
		$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
		$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
	});
	$$('input[id=photo-caption-save]').addEvent('click', function(e) {
		e.stop();
		updateCaption();
	});
	$$('input[id=photo-caption-cancel]').addEvent('click', function(e) {
		e.stop();
		$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
		$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
	});
	$$('a[id=add-caption-link]').addEvent('click', function(e) {
		e.stop();
		$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
		$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
	});
	//init rotate links
	$$('a[id=rotateleftlink]').removeEvents('click');
	$$('a[id=rotateleftlink]').addEvent('click', function(e) {
		e.stop();
		rotatePhoto('left', id);
	});
	$$('a[id=rotaterightlink]').removeEvents('click');
	$$('a[id=rotaterightlink]').addEvent('click', function(e) {
		e.stop();
		rotatePhoto('right', id);
	});
	//init comment text auto grow
	$$('textarea.flext').each(function(el, i) {
		new Flext(el); 
	});
	//init commentbox
	if ($('cmttext')) {
		initCmtBox('cmttext');
		$('commentform').addEvent('submit', function(e) {
			e.stop();
			submitComment('photo');
		});
	}
}

function showAlbumEdit(id) {
	$('album-cell-'+id).getElements('img[class=dashboard-album-edit]').setStyle('display','block');
}
function hideAlbumEdit(id) {
	$('album-cell-'+id).getElements('img[class=dashboard-album-edit]').setStyle('display','none');
}

function editPhotos() {
	var frm = $('form-editphotos');
	frm.getElements('input[id^=delete_]').addEvent('change', function(e) {
		e.stop();
		var pid = this.get('value');
		if (this.get('checked')) {
			frm.getElements('input[id=cover_'+pid+']').set('checked', false);
			frm.getElements('input[id=profile_'+pid+']').set('checked', false);
			frm.getElements('input[id=cover_'+pid+']').set('disabled', true);
			frm.getElements('input[id=profile_'+pid+']').set('disabled', true);
			frm.getElements('textarea[id=caption_'+pid+']').set('disabled', true);
			frm.getElements('select[id=move_'+pid+']').set('disabled', true);
			frm.getElements('select[id=move_'+pid+']').set('value', '');
		}
		else {
			frm.getElements('input[id=cover_'+pid+']').set('disabled', false);
			frm.getElements('input[id=profile_'+pid+']').set('disabled', false);
			frm.getElements('textarea[id=caption_'+pid+']').set('disabled', false);
			frm.getElements('select[id=move_'+pid+']').set('disabled', false);
		}
	});
	frm.getElements('input[id^=cover_]').addEvent('change', function(e) {
		e.stop();
		var pid = this.get('value');
		if (this.get('checked'))
			frm.getElements('select[id=move_'+pid+']').set('value', '');
	});
	frm.getElements('select[id^=move_]').addEvent('change', function(e) {
		e.stop();
		var pid = this.get('id').substr(this.get('id').indexOf('_') + 1);
		frm.getElements('input[id=cover_'+pid+']').set('checked', false);
	});
}

function publishAlbum(aid) {
	var url = sgurlraw+"&func=publishalbum&aid="+aid;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-publish').setStyles({
				'display': 'block',
				'float': 'none',
				'position': 'absolute',
				'left': '240px'
			});
		},
		onSuccess: function(responseText) {
			$('ajax-loading-publish').setStyle('display', 'none');
			$('publish-message').set('html', responseText);
			$('unpublished-album-buttons').destroy();
			$('publish-text').destroy();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

var Paginate = (function(){
	var PaginateSlider = new Class({
		
		Extends: Slider,
		
		initialize: function(element, knob, options){
			this.parent(element, knob, options);
			
			this.drag.addEvents({
				beforeStart: (function(){
					this.isDropping = true;
				}).bind(this),
				complete: (function(){
					this.isDropping = false;
				}).bind(this)
			});
		},
		
		clickedElement: function(event){
			if(this.isDropping) return;
			
			this.parent(event);
		}
		
	});

	return function(){
		$$('div.paginate').each(function(el){
			if(el.retrieve('paginate')) return;
			
			el.store('paginate', true);
			var link = el.getElement('a.link'),
				per = el.getElement('span.per').get('text').toInt(),
				page = el.getElement('span.current').get('text').toInt()-1,
				type = el.getElement('span.type').get('text'),
				init = true;
			
			new PaginateSlider(el.getElement('div.slider'), el.getElement('div.knob'), {
				wheel: false,
				offset: 10,
				steps: link.get('text').toInt()-1,
				onChange: function(step){
					el.getElement('span.current').set('text', step+1);
				},
				onComplete: function(step) {
					var previous = el.getElement('span.previous').get('text').toInt();
					var current = el.getElement('span.current').get('text').toInt();
					if (init)
						init = false;
					else {
						switch (type) {
							case 'latest_albums':
								document.location.hash = "#page="+current;
								changeLatestAlbumPage(type, current, previous);
								break;
							case 'dashboard_photos':
								changeDashboardPhotosPage(type, current, previous);
								break;
							case 'dashboard_albums':
								changeDashboardAlbumsPage(type, current, previous);
								break;
							case 'viewalbum':
								changeViewAlbumPage(type, current, previous);
								break;
							case 'listprofilepics':
								changeListProfilePicsPage(type, current, previous);
								break;
							case 'commentsofalbum':
							case 'commentsofalbums':
							case 'commentsofphotos':
								changeCommentsListPage(type, current);
								break;
						}
					}
					el.getElement('span.previous').set('text', current);
				}
			}).set(page);
		});
	};
})();

function changeLatestAlbumPage(type, page, previouspage) {
	var direction = getDirection(page, previouspage);
	var url = sgurlraw+"&func=changeLatestAlbumPage&page="+page;
	var myReq = new Request.HTML({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('ajax-loading-'+type).setStyle('display','none');
			var Wrapper = $("latestAlbums");
			var oldSlab = Wrapper.getElement('div.slab');
			var newSlab = responseElements[0];
			scrollSlab(Wrapper, oldSlab, newSlab, direction);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeDashboardPhotosPage(type, page, previouspage) {
	var direction = getDirection(page, previouspage);
	var url = sgurlraw+"&func=changeDashboardPhotosPage";
	var myReq = new Request.HTML({
		'url': url,
		'method': 'post',
		'data': {
			'owner': $('owner').get('value'),
			'withme': $('withme').get('value'),
			'page': page
		},
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('ajax-loading-'+type).setStyle('display','none');
			var Wrapper = $('dashboard-photos-cell').getElement('div');
			var oldSlab = Wrapper.getElement('table.slab');
			var newSlab = responseElements[0];
			scrollSlab(Wrapper, oldSlab, newSlab, direction);
			initTips();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeDashboardAlbumsPage(type, page, previouspage) {
	var direction = getDirection(page, previouspage);
	var url = sgurlraw+"&func=changeDashboardAlbumsPage";
	var myReq = new Request.HTML({
		'url': url,
		'method': 'post',
		'data': {
			'owner': $('owner').get('value'),
			'page': page
		},
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('ajax-loading-'+type).setStyle('display','none');
			var Wrapper = $('dashboard-albums-cell').getElement('div');
			var oldSlab = Wrapper.getElement('div.slab');
			var newSlab = new Element('div', {'html': responseHTML}).getChildren()[0];
			scrollSlab(Wrapper, oldSlab, newSlab, direction);

			var newheight = 0;
			newSlab.getChildren('div').each(function(el) {
				if (el.getSize().y > newheight) newheight = el.getSize().y;
			});
			if ($('dashboard-profilepic-cell') && $('dashboard-profilepic-cell').getSize().y != newheight) {
				$('dashboard-profilepic-cell').tween('height',newheight);
			}
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeViewAlbumPage(type, page, previouspage) {
	var direction = getDirection(page, previouspage);
	var tagged = ($('hidden-tagged')) ? "&tagged="+$('hidden-tagged').get('value') : '';
	var url = sgurlraw+"&func=changeViewAlbumPage"+tagged;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'aid': $('album-id').get('value'),
			'page': page
		},
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseJSON, responseText) {
			$('ajax-loading-'+type).setStyle('display','none');
			var Wrapper = $('photos-grid');
			var oldSlab = Wrapper.getElement('table.slab');
			var newSlab = new Element('div', {'html': responseJSON.photos_table}).getChildren()[0];
			scrollSlab(Wrapper, oldSlab, newSlab, direction);

			$('photos-serial').set('html', responseJSON.photos_serial);
			initTips();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeListProfilePicsPage(type, page, previouspage) {
	var direction = getDirection(page, previouspage);
	var tagged = ($('hidden-tagged')) ? "&tagged="+$('hidden-tagged').get('value') : '';
	var url = sgurlraw+"&func=changeListProfilePicsPage"+tagged;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'aid': $('album-id').get('value'),
			'page': page
		},
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseJSON, responseText) {
			$('ajax-loading-'+type).setStyle('display','none');
			var Wrapper = $('photos-grid');
			var oldSlab = Wrapper.getElement('table.slab');
			var newSlab = new Element('div', {'html': responseJSON.photos_table}).getChildren()[0];
			scrollSlab(Wrapper, oldSlab, newSlab, direction);

			$('photos-serial').set('html', responseJSON.photos_serial);
			initTips();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeCommentsListPage(type, page) {
	var task = ($('hidden-task')) ? "&task="+$('hidden-task').get('value') : '';
	var owner = ($('user-id')) ? "&owner="+$('user-id').get('value') : '';
	var aid = ($('album-id')) ? "&aid="+$('album-id').get('value') : '';
	var url = sgurlraw+"&func="+type+task+owner+aid;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'page': page
		},
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseJSON, responseText) {
			$('ajax-loading-'+type).setStyle('display','none');
			$('photos_comments_grid').set('html', responseJSON.comments);
			$('comments-serial').set('html', responseJSON.comments_serial);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function getDirection(current, previous) {
	var direction = '';
	if (current > previous) direction = 'left';
	else direction = 'right';
	return direction;
}

function scrollSlab(Wrapper, oldSlab, newSlab, direction) {
	var size = oldSlab.getSize();
	var newSlabLeft = size.x;
	if (direction == 'right') newSlabLeft = -size.x
	
	newSlab.setStyles({
		left: newSlabLeft
	}).inject(Wrapper, 'bottom');

	var newheight = 0;
	if (newSlab.getSize().y > 0)
		newheight = newSlab.getSize().y;
	else {
		newSlab.getChildren('div').each(function(el) {
			if (el.getSize().y > newheight) newheight = el.getSize().y;
		});
	}
	Wrapper.tween('height',newheight);
	newSlab.getElements('img').addEvent('load', function() {
		newSlab.getChildren('div').each(function(el) {
			if (el.getSize().y > newheight) newheight = el.getSize().y;
		});
		Wrapper.tween('height',newheight);
	});

	var oldSlabSlideout = new Fx.Morph(oldSlab, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
	var newSlabSlidein = new Fx.Morph(newSlab, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
	oldSlabSlideout.start({
		'left': [0, -newSlabLeft]
	}).chain(function(){
		oldSlab.destroy();
	});
	newSlabSlidein.start({
		'left': [0]
	});
}

function makeProfilePic(id) {
	var url = sgurlraw+"&func=makeprofilepic&id="+id;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onSuccess: function(responseJSON, responseText) {
			if ($('headerAvatarThumb'))
				$('headerAvatarThumb').src = responseJSON.headeravatar;
			if ($('commentAvatarThumb'))
				$('commentAvatarThumb').src = responseJSON.commentavatar;
			if (responseJSON.removeprofilepic) {
				$('delete-profile-pic').hide();
				if ($('crop-this-photo')) $('crop-this-photo').show();
				$('make-profile-pic').set('html', responseJSON.removeprofilepic);
				$('make-profile-pic').set('id', 'remove-profile-pic');
			}
			$('comment-table').getElements('.mycomment-thumb').each(function(el) {
				 el.src = responseJSON.commentavatar;
			 });
			Sexy.info(responseJSON.message);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function removeProfilePic() {
	var url = sgurlraw+"&func=removeprofilepic";
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onSuccess: function(responseJSON, responseText) {
			if ($('headerAvatarThumb'))
				$('headerAvatarThumb').src = responseJSON.headeravatar;
			if ($('commentAvatarThumb'))
				$('commentAvatarThumb').src = responseJSON.commentavatar;
			if (responseJSON.makeprofilepic) {
				$('delete-profile-pic').show();
				if ($('crop-this-photo')) $('crop-this-photo').hide();
				$('remove-profile-pic').set('html', responseJSON.makeprofilepic);
				$('remove-profile-pic').set('id', 'make-profile-pic');
			}
			$('comment-table').getElements('.mycomment-thumb').each(function(el) {
				 el.src = responseJSON.commentavatar;
			 });
			Sexy.info(responseJSON.message);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function deleteComment(type, cmtid) {
	var url = sgurlraw+"&func=deletecomment&type="+type+"&cmtid="+cmtid;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
		},
		onSuccess: function(responseText) {
			var el = $('commentRow-'+cmtid);
			var parent = el.getParent('div[class=photo_comments_container]');
			el.destroy();
			if (responseText != '') {
				Sexy.info(responseText);
				return;
			}
			else if (parent != null) {
				var count = parent.getElements('table[class=photo_comments_table]').length;
				if (count == 0)
					parent.destroy();
				var totalcount = $('comment-count').get('html').toInt();
				$('comment-count').set('html', totalcount - 1);
			}
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function gotoPhoto(id, newurl) {
	if ($('detail_panel').hasClass('detail_panel_loading')) return;
	//fix IE7 relative URL error
	var uri1 = new URI(newurl);
	newurl = uri1.toAbsolute();

	document.location.hash = "#"+newurl;
	var url = sgurlraw+"&func=gotophoto&id="+id;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'tagged': $('hidden-tagged').get('value'),
			'withme': $('hidden-withme').get('value'),
			'aid': $('album-id').get('value')
		},
		onRequest: function(){
			$('detail_panel').addClass('detail_panel_loading');
			$('photo-container').setStyle('visibility','hidden');
			$$('div.message').setStyle('display','none');
		},
		onSuccess: function(responseJSON, responseText) {
			var showPhoto = new Element('div', {'html': responseJSON.showPhoto}).getChildren()[0];
			var showPreloadPhotos = new Element('div', {'html': responseJSON.showPreloadPhotos}).getChildren()[0];
			var showData = new Element('div', {'html': responseJSON.showData}).getChildren()[0];
			var showComments = new Element('div', {'html': responseJSON.showComments}).getChildren()[0];
			var showControls = new Element('div', {'html': responseJSON.showControls}).getChildren()[0];
			
			$('prevnext-links').set('html', responseJSON.showPrevNextLinks);
			showPhoto.replaces('photoBlock');
			if (responseJSON.showPreloadPhotos != '')
				showPreloadPhotos.replaces('preload-images');
			showData.replaces('dataBlock');
			if (responseJSON.showComments != '')
				showComments.replaces('commentBlock');
			showControls.replaces('footerControls');
			$('photo-count-string').set('html', responseJSON.photoCountString);
			
			initViewPhoto(id, responseJSON.photo.pid, responseJSON.photo.nid);
			if (responseJSON.tagshash.length) {
				drawTags(responseJSON.photo, responseJSON.tagshash);
				initTagsListEvents();
			}
			$('detail_panel').removeClass('detail_panel_loading');
		},
		onFailure: function(){
			$('detail_panel').removeClass('detail_panel_loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function updateCaption() {
	var textarea = $('photo-caption-edit').getElement('textarea');
	textarea.set('value', textarea.get('value').trim());
	if (textarea.get('value') == $('photo-caption-parent').getElement('input[type=hidden]').get('value')) {
		$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
		$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
		return;
	}
	var url = sgurlraw+"&func=updatecaption&id="+$('currentphoto-id').get('value');
	var myReq = new Request({
		'url': url,
		'method': 'post',
		'data': {
			'caption': textarea.get('value')
		},
		onRequest: function() {
			textarea.set('disabled', 'true');
		},
		onSuccess: function(responseText) {
			$('photo-caption-parent').getElement('input[type=hidden]').set('value', textarea.get('value'));
			textarea.set('disabled', '');
			$('photo-caption').set('html', responseText);
			if (textarea.get('value') == '') {
				$$('a[id=add-caption-link]').addEvent('click', function(e) {
					e.stop();
					$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
					$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
				});
			}
			$('photo-caption-parent').getElement('div[id=photo-caption]').toggle();
			$('photo-caption-parent').getElement('div[id=photo-caption-edit]').toggle();
		},
		onFailure: function(){
			textarea.set('disabled', 'false');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function rotatePhoto(direction,id) {
	if (cropping) return;
	var url = sgurlraw+"&func=rotate&direction="+direction+"&id="+id;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('detail_panel').addClass('detail_panel_loading');
			$('currentphoto').fade('hide');
		},
		onSuccess: function(responseJSON, responseText) {
			var oldwidth = $('photo-container').getStyle('width');
			var oldheight = $('photo-container').getStyle('height');
			$('photo-container').setStyle('width', oldheight);
			$('photo-container').setStyle('height', oldwidth);

			$('detail_panel').removeClass('detail_panel_loading');
			$('currentphoto').set('src', responseJSON.currentphoto);
			$('currentphoto').addEvent('load', function(e) {
				$('currentphoto').fade('in');
			});
			$('Enlarge').set('href', responseJSON.filepath);
			//draw tags if exist
			if (responseJSON.tagshash.length) {
				redrawTags(responseJSON.tagshash);
			}
		},
		onFailure: function(){
			$('detail_panel').removeClass('detail_panel_loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function submitComment(type) {
	if ($('cmttext').get('value').trim() == '') {
		$('commentSubmitBTN').blur();
		new Fx.Tween('cmttext').start('background-color', '#FFEECC');
		return false;
	}

	$('cmttext').setStyle('background-color','#eee');
	$('cmttext').disabled = true;
	var url;
	if (type == 'photo') url = sgurlraw+"&func=commentpic&id="+$('currentphoto-id').get('value');
	else if (type == 'album') url = sgurlraw+"&func=commentalbum&aid="+$('album-id').get('value');
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'cmttext': $('cmttext').get('value')
		},
		onRequest: function() {
			$('ajax-loading-comment').setStyle('display', 'block');
			$('commentSubmitBTN').disabled = true;
		},
		onSuccess: function(responseJSON, responseText) {
			$('ajax-loading-comment').setStyle('display', 'none');
			$('commentSubmitBTN').disabled = false;
			$('flext-button-div').setStyle('display', 'none');
			if (responseJSON.error) {
				Sexy.info(message);
				return;
			}

			$('cmttext').set('value', responseJSON.ghosttext);
			$('cmttext').set('ghosttext', responseJSON.ghosttext);
			$('cmttext').removeEvents();
			new Flext($('cmttext')); 
			$('cmttext').addClass('blurfield');
			$('cmttext').setStyle('background-color','');
			$('cmttext').disabled = false;
			var cmtid = responseJSON.cmtid;
			if (responseJSON.allowed == 1) {
				$('comments-list').set('html', responseJSON.table);
				new Fx.Scroll(window, { 'duration': '0', offset: {'x':0, 'y':-20} }).toElement($('commentRow-'+cmtid)).chain(function() {$('commentRow-'+cmtid).highlight();});
			}
			else {
				if (responseJSON.perms == 3)
					Sexy.info(responseJSON.message);
				else
					requestConn(responseJSON.user_id);
			}
		},
		onFailure: function(){
			$('ajax-loading-comment').setStyle('display', 'none');
			$('commentSubmitBTN').disabled = false;
			$('flext-button-div').setStyle('display', 'none');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function requestConn_Popup(userid, message) {
	Sexy.confirm(message, {
		onComplete: function (returnvalue) {
			if (returnvalue)
				requestConn(userid);
		}
	});
}

function requestConn(userid) {
	var url = sgurlraw+"&func=requestconnection&owner="+userid;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onSuccess: function(responseText) {
			Sexy.info(responseText);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function confirmComment(cmtid, Confirm) {
	var url = (Confirm) ? sgurlraw+"&func=confirmcomment&cmtid="+cmtid : sgurlraw+"&func=ignorecomment&cmtid="+cmtid;
	var row = $('requestComment-'+cmtid);
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function() {
			row.addClass('request-row-loading')
			row.set('html', SG_AJAX_LOADING);
		},
		onSuccess: function(responseJSON, responseText) {
			row.set('html', responseJSON.message);
			row.highlight();
			new Fx.Scroll(window, { 'duration': '0', offset: {'x':0, 'y':-20} }).toElement(row);
			if (responseJSON.error) {
				Sexy.error(responseJSON.message);
				return;
			}
			$('comments-header').set('html', responseJSON.header);
			if ($('sg-comment-request')) { // request module
				if (responseJSON.commentCount) $('sg-comment-request').set('html', responseJSON.moduleMessage);
				else $('request-module-comment').destroy();
			}
			if (responseJSON.tagCount + responseJSON.commentCount == 0) {
				(function() {
					window.location = responseJSON.dashboard;
				}).delay(2000);
			}
		},
		onFailure: function() {
			row.set('html', "<strong style='color:red;'>"+SG_AJAX_ERROR+"</strong>");
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function confirmTag(tagid, Confirm) {
	var url = (Confirm) ? sgurlraw+"&func=confirmtag&tagid="+tagid : sgurlraw+"&func=ignoretag&tagid="+tagid;
	var row = $('requestTag-'+tagid);
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function() {
			row.addClass('request-row-loading')
			row.set('html', SG_AJAX_LOADING);
		},
		onSuccess: function(responseJSON, responseText) {
			row.set('html', responseJSON.message);
			row.highlight();
			new Fx.Scroll(window, { 'duration': '0', offset: {'x':0, 'y':-20} }).toElement(row);
			if (responseJSON.error) {
				Sexy.error(responseJSON.message);
				return;
			}
			$('tags-header').set('html', responseJSON.header);
			if ($('sg-tag-request')) { // request module
				if (responseJSON.tagCount) $('sg-tag-request').set('html', responseJSON.moduleMessage);
				else $('request-module-tag').destroy();
			}
			if (responseJSON.tagCount + responseJSON.commentCount == 0) {
				(function() {
					window.location = responseJSON.dashboard;
				}).delay(2000);
			}
		},
		onFailure: function() {
			row.set('html', "<strong style='color:red;'>"+SG_AJAX_ERROR+"</strong>");
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function ignoreAll() {
	var url = sgurlraw+"&func=ignoreall";
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function() {
			$('sg-ignore-all').set('html', SG_AJAX_LOADING);
		},
		onSuccess: function(responseJSON, responseText) {
			if (responseJSON.error) {
				$('sg-ignore-all').set('html', 'Ignore All');
				Sexy.error(responseJSON.message);
				return;
			}
			$$('.confirmbutton').set('disabled', true);
			$$('.ignorebutton').set('disabled', true);
			Sexy.info(responseJSON.message);
			(function() {
				window.location = responseJSON.dashboard;
			}).delay(2000);
		},
		onFailure: function() {
			$('sg-ignore-all').set('html', 'Ignore All');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function flagPhoto(fpic) {
	var url = sgurlraw+"&func=flagphoto&id="+fpic;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onSuccess: function(responseText) {
			$('flag_div').set('html', responseText);
			var flagnoticeFX = new Fx.Tween('flagnotice');
			flagnoticeFX.set('tween', {duration: 'long'});
			flagnoticeFX.start('background-color', '#ffffff');
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function sgVote(id,rating) {
	if ($('sgvote'+id).innerHTML.indexOf(SG_VOTE_UPDATING) >= 0) return false;
	var url = sgurlraw+"&func=vote";
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'id': id,
			'rating': rating
		},
		onRequest: function() {
			$('sgvote'+id).set('html', '<img src="components/com_simgallery/images/loading.gif" border="0" align="absmiddle" /> '+SG_VOTE_UPDATING);
		},
		onSuccess: function(responseJSON, responseText) {
			var votes = responseJSON.votes;
			var votesum = responseJSON.votesum;
			var message = responseJSON.message;
			var resultstring = responseJSON.resultstring;
			(function() {
				if ($('sgvote'+id)) {
					$('sgvote'+id).set('html', message);
					var percentage = (votesum / votes) * 20;
					$('rating'+id).style.width=percentage+'%';
				}
			}).delay(1000);
			(function() {
				if ($('sgvote'+id))
					$('sgvote'+id).innerHTML='('+resultstring+votes+')';
			}).delay(4000);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function shareAlbum(aid) {
	if ($('share-to').get('value').trim() == '') {
		$('input-div').getElement('ul').setStyle('border', '1px solid red');
		return;
	}
	var message = ($('share-message').get('value') == $('share-message').get('ghosttext')) ? '' : $('share-message').get('value');
	var url = sgurlraw+"&func=sharealbumsubmit&aid="+aid;
	var myReq = new Request({
		'url': url,
		'method': 'post',
		'data': {
			'users': $('share-to').get('value'),
			'message': message
		},
		onRequest: function() {
			$('cpanel-body').getElement('div.footer').addClass('footer-loading');
		},
		onSuccess: function(responseText) {
			$('cpanel-body').getElement('div.footer').removeClass('footer-loading');
			Sexy.info(responseText, {
				onComplete: function() {
					window.parent.Shadowbox.close();
				}
			});
		},
		onFailure: function(){
			$('cpanel-body').getElement('div.footer').removeClass('footer-loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function postToProfile(aid) {
	var url = sgurlraw+"&func=posttoprofilesubmit&aid="+aid;
	var message = ($('share-message').get('value') == $('share-message').get('ghosttext')) ? '' : $('share-message').get('value');
	var myReq = new Request({
		'url': url,
		'method': 'post',
		'data': {
			'message': message
		},
		onRequest: function() {
			$('cpanel-body').getElement('div.footer').addClass('footer-loading');
		},
		onSuccess: function(responseText) {
			$('cpanel-body').getElement('div.footer').removeClass('footer-loading');
			Sexy.info(responseText, {
				onComplete: function() {
					window.parent.Shadowbox.close();
				}
			});
		},
		onFailure: function(){
			$('cpanel-body').getElement('div.footer').removeClass('footer-loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");

		}
	}).send();
}

function initTips() {
	$$(".photoTip").each(function(element,index) {  
		var title = element.get("title");
		if (title == null) return;
		var content = title.split("::");  
		element.store("tip:title", content[0]);  
		element.store("tip:text", content[1]);  
	});  
	var photoTooltip = new Tips($$(".photoTip"), {
		className: "sgtool"
	});
	$$(".hasTip").each(function(element,index) {  
		var title = element.getProperty("title");
		if (title == null) return;
		var content = title.split("::");  
		element.store("tip:title", content[0]);  
		element.store("tip:text", content[1]);
	});  
	var JTooltips = new Tips($$(".hasTip"));
}

var Flext = new Class({
	Implements: Options,
	options: {
		aniTime: 300, 					//int (ms) - grow animation time
		maxHeight: 0,					//int (pixels) - one way to set a max height, if you dont set it via the class.
		defaultMaxHeight: 1000,			//int (pixels) - if not otherwise set, this is the max height
		parentDepth: 6,				//int - how many levels up should to check the parent el's height.
		//trigger classes:
		growClass: 'growme',					//string (class name)- grow the text area
		enterStoppedClass: 'stopenter',			//string (class name)- stop the enter key
		enterSubmitsClass: 'entersubmits',			//string (class name)- submit the form when enter is pressed
		replaceGhostTextClass: 'replaceghosttext',	//string (class name)- tries to use the ghosted text features
		growParentsClass: 'growparents',			//string (class name)- grow the parent elements if needed
		//other attributes:
		ghostTextAttr: 'ghosttext',
		ghostClassAttr: 'ghostclass',
		callbackAttr: 'callback'
	},
	initialize: function(el, options) {
		this.setOptions(options);
		
		this.el = document.id(el); //the textarea element.
		
		//by default, we will do nothing to the text area unless it has the class...
		this.autoGrow = el.hasClass(this.options.growClass);
		this.stopEnter = el.hasClass(this.options.enterStoppedClass);
		this.enterSubmits = el.hasClass(this.options.enterSubmitsClass);
		this.useGhostText = el.hasClass(this.options.replaceGhostTextClass);
		this.growParents = el.hasClass(this.options.growParentsClass);
		
		//initialize, and add events:
		if(this.autoGrow) {
			this.resizer = new Fx.Tween(this.el, {
				duration: this.options.aniTime,
				onComplete: function() {
					var callback = el.get('callback');
					if (callback) {
						eval(callback+'()');	
					}
				}
			});
			this.getMaxSize();
			this.reachedMax = false;
			this.startSize = this.origSize = this.el.getSize().y;
			this.vertPadding = this.el.getStyle('padding-top').toInt()+this.el.getStyle('padding-bottom').toInt()+this.el.getStyle('border-top').toInt()+this.el.getStyle('border-bottom').toInt();
			this.el.setStyle('overflow', 'hidden');
			this.el.addEvents({
				'keyup': function(e) {
					this.checkSize(e);
				}.bind(this),
				'change': function(e) {
					this.checkSize(e);
				}.bind(this),
				'click': function(e) {
					this.checkSize(e);
				}.bind(this)
			});
		
			//get inital state:
			this.checkSize();
		}
		//watch this text area: keydown
		if(this.stopEnter) {
			this.el.addEvent('keydown', function(e) {
				if(e.key == 'enter') {
					e.stop();
					if(this.enterSubmits) {
						this.submitForm();
					}
				}
			}.bind(this));
		}
		//replace ghost text:
		if(this.useGhostText) {
			this.ghostText = this.el.get(this.options.ghostTextAttr);
			this.ghostClass = this.el.get(this.options.ghostClassAttr);
			if(this.ghostText) {
				//initial states: if populated with something else, remove the class:
				if(this.el.get('value') != this.ghostText) {
					this.el.removeClass(this.ghostClass);
				}
				//add events to watch for ghosting:
				this.el.addEvents({
					//remove the ghosted text when the text area receives focus
					'focus': function(e) {
						if(this.el.get('value') == this.ghostText) {
							this.el.set('value', '');
							if(this.ghostClass) {
								this.el.removeClass(this.ghostClass);
							}
							$$('[id=flext-button-div]').setStyle('display', 'block');
						}
					}.bind(this),
					//put the ghost text back if blur'ed and its empty
					'blur': function(e) {
						if(this.el.get('value') == '') {
							this.el.set('value', this.ghostText);
							if(this.ghostClass) {
								this.el.addClass(this.ghostClass);
							}
							$$('[id=flext-button-div]').setStyle('display', 'none');
						}
					}.bind(this)
				});
			}
		}
		
	},
	getMaxSize: function() {
		this.maxSize = this.options.maxHeight;
		if(this.maxSize == 0) {
			var testmax = this.el.className.match(/maxheight-(\d*)/);
			if(testmax) {
				this.maxSize = testmax[1];
			}
			else {
				this.maxSize = this.options.defaultMaxHeight; //if one forgets to set a max height via options or class, use a reasonable number.
			}
		}
	},
	checkSize: function(e) {
		var theSize = this.el.getSize();
		var theScrollSize = this.el.getScrollSize();
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { var checksize = (theScrollSize.y); }
		else var checksize = (theScrollSize.y+this.vertPadding);
		
		if(checksize > theSize.y) {
			//we are scrolling, so grow:
			this.resizeIt(theSize, theScrollSize);
		}
	},
	resizeIt: function(theSize, scrollSize) {
		var newSize = scrollSize.y;
		if((scrollSize.y+this.vertPadding) > this.maxSize && !this.reachedMax) {
			//we've reached the max size, grow to max size and make textarea scrollable again:
			newSize = this.maxSize;
			this.el.setStyle('overflow', '');
			this.resizer.start('height', newSize);
			if(this.growParents) {
				var increasedSize = newSize - this.startSize;
				this.resizeParents(this.el, 0, increasedSize);
			}
			//remember that we've reached the max size:
			this.reachedMax = true;
		}
		if(!this.reachedMax) {
			//grow the text area:
			var increasedSize = newSize - this.startSize;
			if(increasedSize < 0) increasedSize = 0;
			this.startSize = newSize;
			this.resizer.start('height', newSize);
			//resize parent objects if needed:
			if(this.growParents) {
				this.resizeParents(this.el, 0, increasedSize);
			}
		}
	}, 
	resizeParents: function(el, num, incSize) {
		if(num < this.options.parentDepth) {
			var newel = el.getParent();
			if(newel) {
				if(newel.style.height && newel.style.height != '' ) {
					if(newel.retrieve('flextAdjusted')) {
						var newheight = (newel.getStyle('height').toInt()+incSize);
					} else {
						newel.store('flextAdjusted', true); //when resizing parents, the first time we enlarge them we have to include vertical padding
						var newheight = (newel.getStyle('height').toInt()+incSize+this.vertPadding);
					}
					newel.setStyle('height', newheight);
				}
				return this.resizeParents(newel, (num+1), incSize);
			}
			return true;
		} else {
			return true;
		}
	},
	submitForm: function() {
		var thisForm = this.el.getParent('form');
		if(thisForm) {
			var formName = thisForm.get('name');
			document[formName].submit();
			
		}
	}
});

function insertParam(query, key, value) {
    key = escape(key); value = escape(value);

	var p = document.location.search.substr(1);
	var obj = p.parseQueryString();
	var hash = new Hash(obj);
	if (hash.getLength() <= 1)
		document.location = query + '?' + key + '=' +value;
	else
		document.location = query + '&' + key + '=' +value;
}

function sgPopup(el, width, height) {
	Shadowbox.setup(el, {
		'viewportPadding': 0,
		'overlayOpacity': 0,
		'height': height,
		'width': width,
		'displayNav': false,
		'animate': false,
		'top': 0,
		'modal': false,
		'handleOversize': 'none',
		'overlayColor': '#fff',
		'player': 'iframe'
	});
}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email))
		return false;
	else
		return true;
}

//watch the text areas:
window.addEvent('domready', function() {
	$$('textarea.flext').each(function(el, i) {
		new Flext(el); 
	});
});

