/**
// 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.
**/

function makeProfilePic(aid,id) {
	var url = sgurlraw+"&func=makeprofilepic&aid="+aid+"&id="+id;
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function(){
		},
		onSuccess: function(responseJSON, responseText) {
			if ($('headerAvatarThumb'))
				$('headerAvatarThumb').src = responseJSON.headeravatar;
			if ($('commentAvatarThumb'))
				$('commentAvatarThumb').src = responseJSON.commentavatar;
			$('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(aid, id, cmtid) {
	var url = sgurlraw+"&func=deletecomment&aid="+aid+"&id="+id+"&cmtid="+cmtid;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
		},
		onSuccess: function(responseText) {
			$('commentRow-'+cmtid).destroy();
			var count = 1;
			$$("#comment-table > tr").each(function(el) {
				el.setProperty('class','sectiontableentry'+count);
				if (count == 1)
					count = 2;
				else
					count = 1;
			});
			Sexy.info(responseText);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function gotoPhoto(id,browsetype) {
	var func, url;
	func = url = '';
	var aid = $('album-id').value;
	var owner = $('album-owner').value;
	var withme = $('withme').value;
	var currentURL = $('currentURL').value;
	switch (browsetype) {
		case 'normal':
			func = 'detail2';
			url = sgurlraw+"&func=detail2&aid="+aid+"&id="+id+"&currentURL="+currentURL;
			break;
		case 'photosofuser':
			func = 'browsephotos2';
			url = sgurlraw+"&func=browsephotos2&browsetype=photosofuser&owner="+owner+"&withme="+withme+"&id="+id+"&currentURL="+currentURL;
			break;
	}
	var myReq = new Request.HTML({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('detail_panel').addClass('detail_panel_loading');
			$('photo-container').setStyle('visibility','hidden');
			$$('div.message').setStyle('display','none');
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('detail_panel').removeClass('detail_panel_loading');
			$('photo_output').innerHTML = responseHTML;
			if (typeof window['sginit'] == 'function')
				sginit('cmttext');
			sgScriptsInit(id,browsetype);
		},
		onFailure: function(){
			$('detail_panel').removeClass('detail_panel_loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function rotatePhoto(direction,id,browsetype) {
	var aid = $('album-id').value;
	var url = sgurlraw+"&func=rotate&direction="+direction+"&aid="+aid+"&id="+id+"&currentURL="+$('currentURL').value;
	var myReq = new Request.HTML({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('detail_panel').addClass('detail_panel_loading');
			$('currentphoto').fade('out');
		},
		onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('detail_panel').removeClass('detail_panel_loading');
			$('photo_output').innerHTML = responseHTML;
			if (typeof window['sginit'] == 'function')
				sginit('cmttext');
			sgScriptsInit(id,browsetype);
		},
		onFailure: function(){
			$('detail_panel').removeClass('detail_panel_loading');
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function requestConnection(userid) {
	var url = sgurlraw+"&func=requestconnection&owner="+userid;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
		},
		onSuccess: function(responseText) {
			Sexy.info(responseText);
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function submitComment() {
	var cmtEl = $('cmttext');
	var codeEl = $('commentform').getElement('[name=code]');
	cmtEl.setStyle('background-color','');
	if (codeEl)
		codeEl.setStyle('background-color','');
	if (cmtEl.value == '') {
		$('commentSubmitBTN').blur();
		new Fx.Tween(cmtEl).start('background-color', '#FFEECC');
		Sexy.alert(SG_COM_ENTER_COMMENT);
	}
	else if (codeEl && codeEl.value == '') {
		$('commentSubmitBTN').blur();
		new Fx.Tween(codeEl).start('background-color', '#FFEECC');
		Sexy.alert(SG_COM_ENTER_CODE);
	}
	else {
		var code = '';
		if (codeEl)
			code = codeEl.value;
		var url = sgurlraw+"&func=commentpic";
		var myReq = new Request.JSON({
			'url': url,
			'method': 'post',
			'data': {
				'aid': $('album-id').value,
				'id': $('currentphoto-id').value,
				'cmttext': cmtEl.value,
				'code': code
			},
			onRequest: function() {
				$('commentSubmitBTN').addClass('grab-loading');
				$('commentSubmitBTN').disabled = true;
			},
			onSuccess: function(responseJSON, responseText) {
				$('commentSubmitBTN').removeClass('grab-loading');
				if (responseJSON.code == '2') {
					$('commentSubmitBTN').disabled = false;
					Sexy.error(responseJSON.message);
				}
				else {
					cmtEl.value = '';
					cmtEl.disabled = true;
					if (codeEl) {
						codeEl.value = '';
						codeEl.disabled = true;
					}
					var cmtid = responseJSON.cmtid;
					$('commentSubmitBTN').value = responseJSON.button;
					if (responseJSON.allowed == 1) {
						$('comments-list').innerHTML = 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.message);
					}
				}
			},
			onFailure: function(){
				$('commentSubmitBTN').removeClass('grab-loading');
				$('commentSubmitBTN').disabled = false;
				Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
			}
		}).send();
	}
}

function confirmComment(cmtid, aid, id, Confirm) {
	var url = "";
	if (Confirm)
		url = sgurlraw+"&func=confirmcomment&cmtid="+cmtid+"&aid="+aid+"&id="+id;
	else
		url = sgurlraw+"&func=ignorecomment&cmtid="+cmtid+"&aid="+aid+"&id="+id;
	var row = $('requestComment-'+cmtid);
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function() {
			row.addClass('request-row-loading')
			row.innerHTML = SG_AJAX_LOADING;
		},
		onSuccess: function(responseJSON, responseText) {
			new Fx.Scroll(window, { 'duration': '0', offset: {'x':0, 'y':-20} }).toElement(row);
			if (responseJSON.code == 1) {
				$('comments-header').innerHTML = responseJSON.header;
				if ($('sg-comment-request')) {
					if (responseJSON.commentCount > 0)
						$('sg-comment-request').innerHTML = responseJSON.moduleMessage
					else
						$('request-module-comment').destroy();
				}
				if (responseJSON.tagCount + responseJSON.commentCount == 0) {
					setTimeout(function () {
						window.location = responseJSON.sgurl;
					}, 2000);
				}
			}
			else
				Sexy.error(responseJSON.message);
			row.innerHTML = responseJSON.message;
			row.highlight();
		},
		onFailure: function() {
			row.innerHTML = "<strong style='color:red;'>"+SG_AJAX_ERROR+"</strong>";
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function confirmTag(tagid, aid, id, Confirm) {
	var url = "";
	if (Confirm)
		url = sgurlraw+"&func=confirmtag&tagid="+tagid+"&aid="+aid+"&id="+id;
	else
		url = sgurlraw+"&func=ignoretag&tagid="+tagid+"&aid="+aid+"&id="+id;
	var row = $('requestTag-'+tagid);
	var myReq = new Request.JSON({
		'url': url,
		'method': 'get',
		onRequest: function() {
			row.addClass('request-row-loading')
			row.innerHTML = SG_AJAX_LOADING;
		},
		onSuccess: function(responseJSON, responseText) {
			new Fx.Scroll(window, { 'duration': '0', offset: {'x':0, 'y':-20} }).toElement(row);
			if (responseJSON.code == 1) {
				$('tags-header').innerHTML = responseJSON.header;
				if ($('sg-tag-request')) {
					if (responseJSON.tagCount > 0)
						$('sg-tag-request').innerHTML = responseJSON.moduleMessage
					else
						$('request-module-tag').destroy();
				}
				if (responseJSON.tagCount + responseJSON.commentCount == 0) {
					setTimeout(function () {
						window.location = responseJSON.sgurl;
					}, 2000);
				}
			}
			else
				Sexy.error(responseJSON.message);
			row.innerHTML = responseJSON.message;
			row.highlight();
		},
		onFailure: function() {
			row.innerHTML = "<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').innerHTML = SG_AJAX_LOADING;
		},
		onSuccess: function(responseJSON, responseText) {
			if (responseJSON.code == 1) {
				$$('.approvebutton').each(function(el) {
					el.disabled = true;
				});
				Sexy.info(responseJSON.message);
				setTimeout(function () {
					window.location = responseJSON.sgurl;
				}, 2000);
			}
			else {
				$('sg-ignore-all').innerHTML = 'Ignore All';
				Sexy.error(responseJSON.message);
			}
		},
		onFailure: function() {
			$('sg-ignore-all').innerHTML = 'Ignore All';
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function flagPhoto(fuid, fpic) {
	var url = sgurlraw+"&func=flagphoto&fuid="+fuid+"&id="+fpic+"&aid="+$('album-id').value;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onSuccess: function(responseText) {
			$('flag_div').innerHTML = 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(aid,id,rating,vip) {
	var url = sgurlraw+"&func=vote";
	var myReq = new Request.JSON({
		'url': url,
		'method': 'post',
		'data': {
			'aid': aid,
			'id': id,
			'rating': rating,
			'vip': vip
		},
		onRequest: function() {
			$('sgvote'+id).innerHTML = '<img src="'+live_site+'/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;
			setTimeout(function() {
				$('sgvote'+id).innerHTML = message;
				var percentage = (votesum / votes) * 20;
				$('rating'+id).style.width=percentage+'%';
			}, 1000);
			setTimeout(function() {
				$('sgvote'+id).innerHTML='('+resultstring+votes+')';
			}, 3000);
		},
		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':
								changeLatestAlbumPage(type, current);
								break;
							case 'dashboard_photos':
								changeDashboardPhotosPage(type, current);
								break;
							case 'dashboard_albums':
								if (current > previous)
									changeDashboardAlbumsPage(type, current, 'left');
								else
									changeDashboardAlbumsPage(type, current, 'right');
								break;
							case 'view_album':
								changeViewAlbumPage(type, current);
								break;
						}
					}
					el.getElement('span.previous').set('text', current);
				}
			}).set(page);
		});
	};
})();
window.addEvent('domready', Paginate);

function changeLatestAlbumPage(type, page) {
	var url = sgurlraw+"&func=changeLatestAlbumPage&page="+page;
	var latestalbums_list = $('latestAlbums').getElement('div.latestalbums_list');
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
			latestalbums_list.fade('out');
		},
		onSuccess: function(responseText) {
			latestalbums_list.destroy();
			$('latestAlbums').innerHTML = responseText;
			$('ajax-loading-'+type).setStyle('display','none');
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeViewAlbumPage(type, page) {
	var url = sgurlraw+"&func=changeViewAlbumPage&aid="+$('album-id').value+"&page="+page;
	var photos_table = $('photos_table');
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
			photos_table.fade('out');
		},
		onSuccess: function(responseText) {
			var index = responseText.indexOf('###');
			var photos_serial = responseText.substring(0, index);
			var photos = responseText.substring(index+3);
			photos_table.destroy();
			$('photos-serial').innerHTML = photos_serial;
			$('photos-grid').innerHTML = photos;
			$('ajax-loading-'+type).setStyle('display','none');
			initTips();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeDashboardPhotosPage(type, page) {
	var url = sgurlraw+"&func=changeDashboardPhotosPage&owner="+$('owner').value+"&withme="+$('withme').value+"&page="+page;
	var photos_table = $('photos_table');
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
			photos_table.fade('out');
		},
		onSuccess: function(responseText) {
			photos_table.destroy();
			$('dashboard-photos').innerHTML = responseText;
			$('ajax-loading-'+type).setStyle('display','none');
			initTips();
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function changeDashboardAlbumsPage(type, page, direction) {
	var url = sgurlraw+"&func=changeDashboardAlbumsPage&owner="+$('owner').value+"&page="+page;
	var myReq = new Request({
		'url': url,
		'method': 'get',
		onRequest: function(){
			$('ajax-loading-'+type).setStyle('display','block');
		},
		onSuccess: function(responseText) {
			$('ajax-loading-'+type).setStyle('display','none');
			var size = $('albums-wrapper').getSize();
			$('albums-wrapper').addClass('wrapper_old');
			$('albums-wrapper').setProperty('id', 'albums-wrapper-old');
			var wrapper_old = $('albums-wrapper-old');
			if (direction == 'left')
				newWrapperLeft = size.x;
			else
				newWrapperLeft = -size.x;
			var newAlbumsWrapper = new Element('div', {
				'id': 'albums-wrapper',
				'class': 'dashboard-albums-wrapper',
				'html': responseText,
				'styles': {
					'left': newWrapperLeft,
					'width': size.x
				}
			}).inject(wrapper_old, 'after');
			var wrapper_new = newAlbumsWrapper;
			var newSize = wrapper_new.getSize();
			$('dashboard-albums').tween('height',newSize.y);

			var wrapperOldSlideout = new Fx.Morph(wrapper_old, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
			var wrapperNewSlidein = new Fx.Morph(wrapper_new, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
			wrapperOldSlideout.start({
				'left': [6, -newWrapperLeft]
			}).chain(function(){
				$('dashboard-albums').getElements('.wrapper_old').each(function(el) {
					el.destroy();
				});
			});
			wrapperNewSlidein.start({
				'left': [6]
			});
		},
		onFailure: function(){
			Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
		}
	}).send();
}

function grabPhoto(id,message,defaultprompt,error) {
	var selected = null;
	var SexyGrab = new SexyAlertBox({
		OverlayStyles: {
			"opacity": 0.1
		},
		onShowStart: function() {
			var inputbox = $('BoxPromptInput');
			var OKbutton = $('BoxPromptBtnOk');
			inputbox.setStyle('color','#808080');
			inputbox.addEvent('focus', function(e) {
				e.stop();
				if (inputbox.getProperty('value') == defaultprompt) {
					inputbox.setProperty('value','');
					inputbox.setStyle('color','');
				}
			});
			inputbox.addEvent('blur', function(e) {
				e.stop();
				if (inputbox.getProperty('value') == '') {
					inputbox.setProperty('value',defaultprompt);
					inputbox.setStyle('color','#808080');
				}
			});
			if (error) {
				new Element('div', {
					'html': SG_GRAB_ALBUM_CANNOT_BLANK,
					'styles': {
						'padding': '3px',
						'margin': '3px',
						'background-color': '#FFF3A3',
						'color': '#B79000'
					}
				}).inject($('SexyAlertBox-Buttons'),'before');
			}
			inputbox.fade('hide');
			var url = sgurlraw+"&func=getalbumslist";
			var myReq = new Request.JSON({
				'url': url,
				'method': 'get',
				onRequest: function(){
				},
				onSuccess: function(responseJSON, responseText) {
					inputbox.fade('show');
					var albumsdropdown = new Element('select', {
						'id': 'albumsdropdown',
						'class': 'small',
						'events': {
							'change': function() {
								selected = albumsdropdown.value;
								if (selected == 0) {
									inputbox.fade('show');
									inputbox.setProperty('value',defaultprompt);
									inputbox.setStyle('color','#808080');
								}
								else {
									inputbox.setProperty('value',selected);
									inputbox.fade('hide');
								}
							}
						}
					}).inject(inputbox,'before');
					new Element('br').inject(albumsdropdown,'after');
					
					responseJSON.each(function(album) {
						new Element('option', {
							'value': album.aid,
							'text': album.name
						}).inject(albumsdropdown,'bottom');
					});
					
					$('grab-loading').destroy();
				},
				onFailure: function(){
					Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
				}
			}).send();
		}
	});
	
	SexyGrab.prompt(message, defaultprompt, {
		onComplete: function(returnvalue) {
			if (returnvalue === false)
				return false;
			else if (returnvalue == defaultprompt || returnvalue === '') {
				grabPhoto(id,message,defaultprompt,true);
			}
			else {
				var url = sgurlraw+"&func=grabphoto&id="+id+"&aid="+$('album-id').value+"&selected="+selected+"&albumName="+returnvalue;
				var myReq = new Request.JSON({
					'url': url,
					'method': 'get',
					onRequest: function(){
						$('grab-link').addClass('grab-loading');
						$('grab-link').innerHTML = SG_GRAB_GRABBING;
					},
					onSuccess: function(responseJSON, responseText) {
						$('grab-link').removeClass('grab-loading');
						if (responseJSON.code == '1') {
							$('grab-link').innerHTML = responseJSON.grab_link;
							Sexy.info(responseJSON.message);
						}
						else if (responseJSON.code == '2') {
							Sexy.error(responseJSON.message);
						}
					},
					onFailure: function(){
						$('grab-link').innerHTML = '<a onclick="grabPhoto(id,message,defaultprompt,error);">'+SG_PHOTO_GRAB_PHOTO+'</a>';
						Sexy.error("<strong>"+SG_AJAX_ERROR+"</strong>");
					}
				}).send();
			}
		}
	});
}

function sgScriptsInit(id,browsetype) {
	var aid = $('album-id').value;
	var owner = $('album-owner').value;
	if (typeof window['initNextPrevLinks'] == 'function')
		initNextPrevLinks();
	if (typeof(tagging) != "undefined") {
		if (sg_pro) {
			container = $("photo-container");
			notes = new PhotoNoteContainer(container);
			if (typeof window['drawTags'] == 'function')
				drawTags();
		}
	}
	$('currentphoto').addEvent('click', function(e){
		if (tagging && sg_pro) {
			e.stop();
			addTag(e.page.x, e.page.y, id);
		}
		else {
			if (parseInt($('previousphoto-id').value) + parseInt($('nextphoto-id').value) != 0)
				gotoPhoto($('nextphoto-id').value,browsetype);
		}
	});
	if ($('commentform')) {
		$('commentform').addEvent('submit', function(e) {
			e.stop();
			submitComment();
		});
	}
}

function initTips() {
	$$(".sgTips").each(function(element,index) {
		var content = element.get("title").split("::");  
		element.store("tip:title", content[0]);  
		element.store("tip:text", content[1]);  
	});  
	var sgTips = new Tips($$(".sgTips"), {
		className: "sgtool"
	});
}

