var autoSave = false;
var cancel = false;
var isNewAvatar = false;
var isAvatar = false;
var oldAvatarUrl = '';
var newAvatarUrl = '';

function checkStep4()
{
	var site = $F('website').strip().toLowerCase();
	if (site != '' && site.indexOf('http://') != 0 && site.indexOf('https://') != 0) {
		$('website').value = 'http://' + site;
		if ($F('website').length > 60) {
			alert('Website should be less than 60 characters.');
			$('website').focus();
			return false;
		}
	}
	var myspace = $F('myspace').strip().toLowerCase();
	var regexp = /^[a-zA-Z0-9_]+$/i;
	if (myspace != '' && !regexp.test(myspace)) {
		alert('Only letters, numbers and "_" allowed for MySpace ID.');
		$('myspace').focus();
		return false;
	}
	return true;
}

function checkStep5()
{
	var p1 = $F('ProfilePassword'), p2 = $F('ProfilePassword2');
	if (p1 != '' || p2 != '') {
		if (p1.length < 6 || p1.length > 20) {
			alert('Please enter new password between 6 and 20 characters long.');
			$('ProfilePassword').focus();
			return false;
		} else if (p1 != p2) {
			alert('Verify password must be the same as new password.');
			$('ProfilePassword2').focus();
			return false;
		}		
	}
	var email = $F('ProfileEmail').strip();
	if (email != '' && !$VP.EMAIL.test(email)) {
		alert('Please enter a valid email address.');
		$('ProfileEmail').focus();
		return false;
	}
	return true;
}

function done() 
{
	if (checkStep4() && checkStep5()) {
		if(!isFlash() && multi_selector.count > 1){
			selectStep(2);
			autoSave = true;
			uploadSubmit();
			return;
		} 
		if (isNewAvatar) {
			autoSave = true;
			uploadSubmit(true);
			return;
		}
		formSubmit();
	}
}

function isFlash() 
{
	return $('FlashFilesUpload');
}

/* Copy step1-form fields to post-form. */
function copyStep1FormFields() 
{
	var toInputs = Form.getInputs('profile-form', 'hidden');
	var gotIt = false;
	var el = $('about_you');

	gotIt = false;
	toInputs.each(function (to) {
		if (to.name == el.name) {	//Exists, then change the value.
			to.value = el.value;
			gotIt = true;
		}	//end if
	});

	if (!gotIt) {	//Doesn't exist, then create a hidden input field.
		var hidden = document.createElement('input');
		hidden.type  = "hidden";
		hidden.name  = el.name;
		hidden.value = el.value;
		$('profile-form').appendChild(hidden);
	}	//end if
}

function formSubmit()
{
	try	{
		copyStep1FormFields();
		$("sorting_input").value = Sortable.serialize("sortable_photos");
		$("deleted_input").value = deletedPhotos.toString();
	}
	catch(e) { }
	finally	{
		selectStep(1);
		$('preview_message').hide();
		Element.show('edit_do');
		$('edit_cancel').hide();
		new Effect.SlideUp('editpost', {
			duration:1,
			afterFinish: function() {
				$('profile-form').submit();
			}
		});		
	}
}

function uploadSubmit(is_avatar)
{
	if (is_avatar) {
		if (!$F('avatar-file')) return;
		var f = $('step1-form');
		f.action = webroot + 'users/upload/' + user_id + '/1/1';
		isAvatar = true;
	} else {
		if (!isFlash() && multi_selector.count > 1) {
			var f = $('step2-form');
			f.action = webroot + 'users/upload/' + user_id + '/1';
			isAvatar = false;		
		} else {
			return false;
		}
	}
	// g_user_id = user_id;	
	f.target = 'upload_iframe';
	uploadLoading();
	f.submit();
}

function uploadLoading()
{
	if (isAvatar) {
		Form.Element.disable('avatar_btn_upload');
		$('avatar_upload_message').update('Uploading ....');
	} else {
		Form.Element.disable('btn_upload');
		$('upload_message').update('Uploading ....');		
	}
}

function uploadDone(error_type)
{
	isNewAvatar = false;
	if (isAvatar) {
		Form.Element.enable('avatar_btn_upload');
		el = $('avatar_upload_message');
	} else {
		newPhotos = true;		
		Form.Element.enable('btn_upload');
		if (multi_selector)
			multi_selector.removeAll();	
		el = $('upload_message');
	}

	if (error_type==2) {
		el.update('Error occured while uploading one of the files (not an image) !');
		return;
	}
	else if (error_type==1) {
		el.update('Error occured while uploading one of the files (corrupted file) !');
		return;
	}
	else {
		el.update('Done.');
		if (!isAvatar) {
			toStep3();
		} else {
			window.forms_changed = true;
			if (autoSave) {
				formSubmit(); 
				return; 
			}
			if (newAvatarUrl) {
				$('edit-avatar').src = newAvatarUrl;
				// console.log('new avatar: ' + $('edit-avatar').src);
			}
			preview.show();
		}
	}	//end if
}

var targetStep = -1;
function selectStep(id)
{
	if ($('step4').visible() && !checkStep4()) {
		return;
	}
	if ($('step5').visible() && !checkStep5()) {
		return;
	}
	
	// if (!cancel && Element.visible('step2') && isFlash() && uploadSelectedFiles()) {
	// 	targetStep = id;
	// 	return;	//uploading files. waiting ....
	// }
	if (Element.visible('step1')) {
		uploadSubmit(true);	//upload avatar
	}
	if(window.forms_changed) { //Refresh the preview - if any field was modified
		preview.show();
		forms_changed=false;
	}
	for(i=1; i<=5; i++)
	{
		$('step'+i).style.display = 'none';
		$('link_step'+i).className = 'notselected';
	}
	$('step'+id).style.display = 'block';
	$('link_step'+id).className = 'selected';
	if(id==4) scroller.init();
	//if(id==2) Element.update('upload_message', '');
	handleChanges();
}

function openUploader()
{
	var url = webroot + 'users/uploader/' + user_id ;
	var w = 670, h = 340, l, t;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	var win = window.open(url, 'uploader', 
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,' +
				'width=' + w + ',height=' + h + ',left=' + l + ',top=' + t);
	if (!win) {
		alert("Could not open a new window. Please allow popup window for this site.");
	} else {
		win.resizeTo(w, h);
		win.moveTo(l, t);
		win.focus();
	}
}

//current selected photo's index
var gCurrentPhotoIndex = -1;
var deletedPhotos = Array();
var thumbs = [];

function showCaption(photo_index)
{
	if (gCurrentPhotoIndex > 0 && $('photo_'+gCurrentPhotoIndex)) {
		$('photo_'+gCurrentPhotoIndex).removeClassName('selected');
		$('caption_'+gCurrentPhotoIndex).hide();		
	}
	$('photo_'+photo_index).addClassName('selected');
	$('caption_'+photo_index).show();		
	gCurrentPhotoIndex = photo_index;
	var number = thumbs.indexOf(photo_index)+1;
	$('photo_number').update(number + '/' + thumbs.length);

	if ($('scroller-wrap').visible())
		photo_scroller.moveToElement($('photo_'+photo_index));
}

function showCaptionIcon(photo_index)
{
	var icon = 'caption_icon_'+photo_index;

	if (!$(icon)) return false;
	if ($('caption_'+photo_index) && $F('caption_'+photo_index)) {
		$(icon).addClassName('caption_icon_filled');
	} else {
		$(icon).removeClassName('caption_icon_filled');
	}
}

function initSortable()
{
	Sortable.create('sortable_photos', {tag:'div', constraint:false, overlap:'horizontal', 
		onUpdate:function() {
			forms_changed = true;
		}});
}

//image controls for add/edit post step 3
var imageControls = {
	currentId: null,
	previousId: null,	
	nextId: null,
	firstId: null,
	lastId: null,
	init: function() {
		this.currentId = gCurrentPhotoIndex;
		var idSequence = Sortable.sequence('sortable_photos');
		idSequence = idSequence.without(deletedPhotos.toString());
		this.firstId = idSequence.first();
		this.lastId = idSequence.last();
		var currentIndex = idSequence.indexOf(this.currentId);
		this.previousId = idSequence[currentIndex-1];
		this.nextId = idSequence[currentIndex+1];
	},
	previous: function() {
		this.init();
		var preId = null;		
		if(this.currentId == this.firstId)
			preId = this.lastId;
		else {
		 	preId = this.previousId;	
		}
		showCaption(preId);
	},
	next: function() {
		this.init();
		var nextId = null;		
		if(this.currentId == this.lastId)
			nextId = this.firstId;
		else {
		 	nextId = this.nextId;	
		}
		showCaption(nextId);
	},
	del: function() {
		if(confirm('Are you sure, you want to delete this photo ? '))
		{
			this.init();
			$("caption_"+this.currentId).value = "";
			$('photo_' + this.currentId).hide();
			$('photospan_' + this.currentId).hide();
			//deletedPhotos.push(this.currentId);
			var URL = webroot + "users/delete_photo/" + this.currentId;
			new Ajax.Request(URL, {
				asynchronous: true, 
				evalScripts: true,
				onComplete: function() {
					this.next();
					window.forms_changed = true; 
					preview.show(); }.bind(this)
			});
		}
	}
};

var viewContent = '';
var forms_changed = false;

function handleChanges() {
	var fields = $("steps").getElementsByTagName("input");
	for(var i=0;i<fields.length; i++) {
		//Ahsan: changed the code below to prototype event handler, as prototype adds rather than over-write the handler
		//needed to do this coz there is a need to add more onchange events
		Event.observe(fields[i], 'change', function() {window.forms_changed = true});
	}
	var textareas = $("steps").getElementsByTagName("textarea");
	for(var i=0;i<textareas.length; i++) {
		Event.observe(textareas[i], 'change', function() {window.forms_changed = true});
	}
}

function cancelEdit()
{
	if (!confirm('Are you sure you want to cancel? You will lose all of your changes.')) return;
	$('step1-form').reset();
	$('profile-form').reset();
	$('edit-avatar').src = oldAvatarUrl;
	$('avatar_upload_message').update('');
	$('avatar-buttons').hide();	
	// console.log('reset avatar: ' + $('edit-avatar').src);
	slideUp();
	new Ajax.Request(webroot+'users/cancel/');
}

function slideUp()
{
	$('preview_message').hide();
	selectStep(1);
	Element.show('edit_do');
	$('edit_cancel').hide();
	new Effect.SlideUp('editpost', {
		duration:1,
		afterFinish: function() {
			//hide the preview
			Element.hide('preview-container');
			Element.update('preview-container', '');
			
			//show the previous post, since nothing changed
			Element.update('view-container', viewContent);
			Element.show('view-container');
			
			forms_changed = false;
			selectStep(1);
			
			if (multi_selector)
				multi_selector.removeAll();	
			
			//restart the slideshow, to change the position of the next/previous button
			if(SlideShow.slides.length!=0) SlideShow.show();
		}
	});
	
	//Element.hide('edit_cancel');
}

function slideDown()
{
	
	//Element.show('edit_cancel');
	new Effect.SlideDown('editpost', {
		duration:1,
		afterFinish: function() {
			Element.hide('edit_do');
			$('edit_cancel').show();
			$('preview_message').show();
			//save the content of the current post view to e shown again if no changes made			
			if (!viewContent)
				viewContent = $('view-container').innerHTML;
			//to detect if changes are made, to know when or when not to load the preview
			handleChanges();
			//restart the slideshow, to change the position of the next/previous button
			//alert(SlideShow.slides.length);
			if(SlideShow.slides.length!=0)SlideShow.show();
		}
	});
}



var IdCreator = Class.create();
Object.extend(IdCreator.prototype, {
	seq: 0,

	initialize: function(prefix, idKeys) {
		this.prefix = prefix || 'id';
		this.idKeys = idKeys || [];
	},

	getId: function() {	//create a new id
		return ++this.seq;
	},

	getPrefix: function(key) {
		return this.prefix + '_' + key + '_';
	},

	getRealId: function(id) {
		var realId = '';

		this.idKeys.each((function (v) {
			var prefix = this.getPrefix(v);
			if (id.indexOf(prefix) != -1)
				realId = id.replace(prefix, '');
		}).bind(this));
		return realId;
	},

	getIds: function(id) {
		var h = $H();

		this.idKeys.each((function (v) {
			h[v] = this.getPrefix(v) + id;
		}).bind(this));
		return h;
	}
});

var scroller = {
	slider: null,
	init: function() {
		var slider = new Control.Slider('profile-handle', 'profile-scroller', {
				axis: 'vertical',
				onSlide: function(v) { scroller.scrollVertical(v, $('profile-more-div'), slider);  },
				onChange: function(v) { scroller.scrollVertical(v, $('profile-more-div'), slider); }
			});	
		this.slider = slider;
	},
	scrollVertical: function(value, element, slider){
		element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));	
	},
	up: function() {
		if(this.slider.value>0) {
			this.scrollVertical(this.slider.value-0.1, $('profile-more-div'), this.slider);
			this.slider.setValue(this.slider.value - 0.1, 0);
		}	
	},
	down: function() {
		if(this.slider.value<1) {
			this.scrollVertical(this.slider.value+0.1, $('profile-more-div'), this.slider);
			this.slider.setValue(this.slider.value + 0.1, 0);
		}
	}
};

var photo_scroller = {
	slider: null,
	init: function() {
		var slider = new Control.Slider('handle', 'scroller', {
				axis: 'vertical',
				onSlide: function(v) { this.scrollVertical(v);  }.bind(this),
				onChange: function(v) { this.scrollVertical(v); }.bind(this)
			});	
		this.slider = slider;
		this.element = $('sortable_photos');
	},
	scrollVertical: function(value){
		this.element.scrollTop = Math.round(value/this.slider.maximum*(this.element.scrollHeight-this.element.offsetHeight));	
	},
	scrollTo: function(value)
	{
		this.scrollVertical(value);
		this.slider.setValue(value, 0);
	},
	up: function() {
		if(this.slider.value>0) {
			this.scrollTo(this.slider.value-0.3);
		}	
	},
	down: function(event) {
		if(this.slider.value<1) {
			this.scrollTo(this.slider.value+0.3);
		}
	},
	moveToElement: function(element) {
		var offsets, elementTop, scrollTop, containerTop, realTop, value;

		offsets = Position.cumulativeOffset(element);
		elementTop = offsets[1];
		offsets = Position.cumulativeOffset($('sortable_photos'));
		containerTop = offsets[1];
		scrollTop = $('sortable_photos').scrollTop;
		realTop = elementTop - scrollTop - containerTop;
		value = this.slider.translateToValue(realTop);
		if (realTop < 0 || realTop > 136) {	//	68/row
			this.scrollTo(value);
		}
	}
};

function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength) {
		obj.value=obj.value.substring(0,mlength);
		alert("Cannot be more that 700 characters")
	}
}

var preview = {
	before: function() {
		copyStep1FormFields();
		try {
			//$("sorting_input").value = Sortable.serialize("sortable_photos");
			//$("deleted_input").value = deleted_photos;
		} catch(e) { }
	},
	show: function(scroll) {
		preview.before();
		if (scroll == undefined) {
			scroll = false;
		}
		if (window.forms_changed) {
			window.forms_changed = false; //Reset for next step.
			new Ajax.Updater('preview-container', webroot+'users/preview', {
				asynchronous:true, 
				evalScripts:true,
				onComplete:function(request){
					preview.after(scroll);
				},
				parameters:Form.serialize("profile-form"),
				requestHeaders:['X-Update', 'preview-container']		
			}, false);					
		} else if (scroll) {
			Element.scrollTo('edit-controls');
		}
	},
	after: function(scroll) {
		Element.show("preview-container");
		Element.hide('view-container');
		if (scroll)
			Element.scrollTo('edit-controls');
	}
};

var isPreview = false;
function showPreview() 
{
	if (!cancel && Element.visible('step2') && isFlash() && uploadSelectedFiles()) {
		isPreview = true;
		return;
	}
	preview.show(true);
}

var SlideShow = {
	slides: [],	//array of photos' id
	srcs: [],	//array of big photos' src
	
	captions: [],
	
	images: [],
	pages: 1,	//total pages
	page: 1,	//curent page
	rows: 24,	//photos number per page
	slide: 0,	//current slide
	userId: 0,	//post id
	showCmd: 'next', 	//last show command
	
	setPages: function(pages) {
		this.pages = pages;
		this.resetPagination();
	},
	
	setCurrentPage: function(page) {
		this.page = page;
		this.resetPagination();
	},
	
	resetPagination: function() {
		Element.hide('prev-photo-page'); Element.hide('next-photo-page');
		if (this.page > 1)
			Element.show('prev-photo-page');
		if (this.page < this.pages)
			Element.show('next-photo-page');
	},
	
	setUserId: function(userId) {
		this.userId = userId;
	},
	
	addSlide: function(id) {
		this.slides.push(id);
	},
	
	addSlideSrc: function(src) {
		this.srcs.push(src);
	},
	
	addCaption: function(caption) {
		this.captions.push(caption);
	},
	
	setCurrentSlide: function(id) {
		if (this.slides.indexOf(id) == -1)
			return false;
		this.slide = id;
		return true;
	},
	
	emptySlides: function() {
		this.slides = [];
		this.srcs = [];
	},
	
	initActions: function() {
		//Prev/Next on large photo
		Element.hide('slide-prev'); Element.hide('slide-next');
		Event.observe('slide-prev' , 'click'   , function(e) { this.prev(); Event.stop(e); }.bind(this));
		Event.observe('slide-next' , 'click'   , function(e) { this.next(); Event.stop(e); }.bind(this));

	},
	
	initPosition: function() {
		var pos = Position.cumulativeOffset($('large_photo'));
		var l = pos[0], t = pos[1];
		var h = $('large_photo').height, w = $('large_photo').width;
		Element.setStyle('link-box', {
			'left'	: (l+1) + 'px', 
			'top'	: t + 'px', 
			'width'	: (w+1) + 'px', 
			'height': h + 'px' });
	},
	
	show: function(id) {
		if (!id) {
			id = (this.showCmd == 'next') ? this.slides.first() : this.slides.last();
		}
		Element.hide('slide-prev');
		Element.hide('slide-next');
		
		//change the selected thumb style and some information
		Element.update('img_caption', this.captions[this.slides.indexOf(id)]);
		Element.update('img_number', this.slides.indexOf(id) + 1);
		this.setCurrentSlide(id);
		//change the large photo's source
		var idx = this.slides.indexOf(id);
		if (this.images[idx].complete) {
			this._show(this.images[idx]);
		} else {
			Element.hide('large_photo');
			Element.show('loading-big-photo');
			this.images[idx].onload = function() { 
				if (this.slide == this.slides[idx])
					this._show(this.images[idx]);
			}.bind(this);
		}
	},
	
	_show: function(img) {
		Element.hide('loading-big-photo');
		$('large_photo').src = img.src;
		$('large_photo').width = img.width;		//for Safari 
		$('large_photo').height = img.height;	//for Safari 
		Element.show('large_photo');
		this.initPosition();
		this.resetButtons();
	},
	
	preload: function() {
		this.srcs.each(function(src, index) {
			this.images[index] = new Image();
			this.images[index].src = src;
		}.bind(this));
	},
	
	isFirst: function() {
		return (this.slides.indexOf(this.slide) <= 0) && (this.page <= 1);
	},
	
	isLast: function() {
		return (this.slides.indexOf(this.slide) >= this.slides.length-1) && (this.page == this.pages);
	},
	
	prev: function() {
		var idx = this.slides.indexOf(this.slide);
		this.showCmd = 'prev';
		if (idx > 0) {
			this.show(this.slides[idx-1]);
			this.resetButtons();
		} else if (!this.isFirst()) {
			this.prevPage();
		}
	},
	
	next: function() {
		var idx = this.slides.indexOf(this.slide);
		this.showCmd = 'next';
		if (idx > -1 && idx < this.slides.length-1) {
			this.show(this.slides[idx+1]);
			this.resetButtons();			
		} else if (!this.isLast()) {
			this.nextPage();
		}
	},
	
	resetButtons: function() {
		if (this.isFirst())
			Element.hide('slide-prev');
		else
			Element.show('slide-prev');
		if (this.isLast())
			Element.hide('slide-next');		
		else
			Element.show('slide-next');		
	},
	
	prevPage: function() {
		new Ajax.Updater(
			'thumbs', 
			webroot+'posts/photos/'+this.postId+'/'+(this.page-1), 
			{asynchronous:true, evalScripts:true, 
				onLoading: function(){ Element.show('loading-photos'); },
				onComplete: function(){ Element.hide('loading-photos'); this.resetButtons(); }, requestHeaders:['X-Update', 'thumbs']});		
	},
	
	nextPage: function() {
		new Ajax.Updater(
			'thumbs', 
			webroot+'posts/photos/'+this.postId+'/'+(this.page+1), 
			{asynchronous:true, evalScripts:true, 
				onLoading: function(){ Element.show('loading-photos'); },
				onComplete: function(){ Element.hide('loading-photos'); this.resetButtons(); }, requestHeaders:['X-Update', 'thumbs']});		
	}
};

var newPhotos = true;
function loadPhotos() {
	if (!newPhotos) {
		$('loading_step3').hide();		
		$('showphotos').show();		
		return false;
	}
	$('showphotos').hide();
	$('loading_step3').show();
	new Ajax.Updater('showphotos', webroot+'users/showphotos/'+user_id, {
	 	onComplete:function(request){
			$('loading_step3').hide();		
			$('showphotos').show();
			photo_scroller.init();
			handleChanges();
			newPhotos = false;
		}, asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'showphotos']});
	return true;
}

function toStep3() 
{
	//this is needed for automate from step 2 to step 3 after successfull upload
	selectStep(3);	
	loadPhotos();
	if(autoSave) formSubmit();
}

var upload_completed = false;
function MultiPowUpload_onCompleteAbsolute(type, uploadedBytes)
{
	forms_changed = true;
	upload_completed = true;
	newPhotos = true;	
	if ([1,4,5].indexOf(targetStep) != -1) {
		selectStep(targetStep);
		targetStep = 0;
	} else {
		toStep3();
	}
	if (isPreview) {
		isPreview = false;
		preview.show(true);
	}
}

function MultiPowUpload_onSelect()
{
	upload_completed = false;
}

function MultiPowUpload_onError(error)
{
	window.alert(error);
}

/**
 * Auto upload the selected files when user click next step.
 * @return boolean Return true if need to upload files, else return false.
 */
function uploadSelectedFiles()
{
	try {
		var files = Flash.fileList();		
		if (files.length > 0 && !upload_completed) {
			Flash.uploadAll();
			return true;
		}
	} catch(e) {
		//
	}
	return false;
}
