//media ratings
var Rating = {
	//add rating
	add: function(event) {
		var rating = $(this);
		$$('a.addrating').invoke('hide');
		var id = rating.readAttribute('ratingid');
		var value = rating.readAttribute('ratingvalue');
		$('unit_ulrateStars').down('li.current-rating').setStyle({width:(value * 27)+'px'});
		var url = '/_ajax/ratings/add.php';
		new Ajax.Request(url, 
			{
		  		method: 'get',
		  		parameters: 'id='+id+'&rating='+value,
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText != 'OK')
		  			{
		  				messageBox('There was an error while rating.');
		  			}
		  		}
			}
		);
		Event.stop(event);
		window.setTimeout(function(){
			Rating.setText('Thanks for voting!');
			window.setTimeout("$('ratingText').fade()", 1000);
		}, 100);
	},
	//mouseover
	mouseOver: function(event)
	{
		Rating.setText(this.readAttribute('ratingtext'));
	},
	//mouseout
	mouseOut: function(event)
	{
		Rating.setText('&nbsp;');
	},
	//set rating text
	setText: function(text)
	{
		$('ratingText').update(text);
	},
	//on load
	setEventObserver: function(event) {
		$$('a.addrating').invoke('observe', 'click', Rating.add);
		$$('a.addrating').invoke('observe', 'mouseover', Rating.mouseOver);
		$$('a.addrating').invoke('observe', 'mouseout', Rating.mouseOut);
	}
}

//media tags
var Tag = {
	//remove tag
	remove: function(event) {
		tag = $(this);
		tagId = tag.readAttribute('tagid');
		tag.up('li').hide();
		var url = '/_ajax/tags/remove.php';
		new Ajax.Request(url, 
			{
		  		method: 'get',
		  		parameters: 'id='+tagId,
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText == 'KO')
		  			{
		  				messageBox('There was an error while removing your tag.');
		  			}
		  		}
			}
		);
		Event.stop(event);
	},
	//add tags
	add: function(pars, form) {
		// Validation
		var testContestTerms, tag;
        // Check for 3DVIA Challenge tags
		if(tag = form.tags.value.match(/3dviachallenge[\d]+/)) {
        	var contestText = "By adding the \"" + tag  + "\" tag to your model, you are acknowledging that you have read and agree to the Terms & Conditions that govern this contest. If this is not your intention, please click \"Cancel\" and remove the tag from your model.";

            testContestTerms = confirm(contestText);
            if(testContestTerms == false) { // If the user does not agree to the terms
		  		form.enable();
				form.select('img.spinner').invoke('hide'); 
                form.focusFirstElement();
                return false;
            }
        }


		var url = '/_ajax/tags/add.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
		  		onSuccess: function(data)
		  		{
		  			if(typeof(form) != 'undefined') 
		  			{
						form.select('img.spinner').invoke('hide'); 
						form.reset();
		  				form.enable();
		  				form.focusFirstElement();
					}
					if($('tags')) $('tags').insert(data.responseText);
					Tag.setEventObserver();
		  		}
			}
		);
	},
	//add tags from a form
	addForm: function(event) {
		form = $(this);
		form.select('img.spinner').invoke('show'); 
		Tag.add(form.serialize(), form);
		form.disable();
		Event.stop(event);
	},
	//observe events
	setEventObserver: function(event) {
		$$('a.removetag').invoke('observe', 'click', Tag.remove);
		Tag.toggleAddTags(event);
		if($('openAddTags'))
			$('openAddTags').observe('click', Tag.toggleAddTags);
		if($('frmAddTags'))
			Event.observe('frmAddTags', 'submit', Tag.addForm);
	},
	//open add tags form
	toggleAddTags: function(event) {
		if($('openAddTags'))
			$('openAddTags').toggle();
		if($('frmAddTags'))
		{
			$('frmAddTags').toggle();
			$('frmAddTags').focusFirstElement();
		}
		Event.stop(event);
	}
}

//media comments
var Comment = {
	Data: [],
	//add comment
	add: function(pars, form) {
		if($('checkSubscribeComments') && $('checkSubscribeComments').checked)
		{
			$('comment_subscribe').addClassName('on');
			Comment.subscribeUpdate();
		}
		else if($('checkSubscribeComments') && !$('checkSubscribeComments').checked)
		{
			$('comment_subscribe').removeClassName('on');
			Comment.subscribeUpdate();
		}
		var url = '/_ajax/comments/add.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
		  		onSuccess: function(data)
		  		{
		  			if(typeof(form) != 'undefined') 
		  			{
						form.select('img.spinner').invoke('hide'); 
						form.reset();
		  				form.enable();
		  				form.focusFirstElement();
					}
					if($('comments')) $('comments').insert(data.responseText);
					Comment.setEventObserver();
		  		}
			}
		);
	},
	//edit comment
	edit: function(event) {
		comment = $(this);
		commentid = comment.up('div.comment').readAttribute('commentid');
		$('textilized'+commentid).hide();
	},
	//edit comment enter edit mode
	editEnterEditMode: function(form, value) {
		id = form.element.getAttribute('commentid');
		Comment.Data[id] = form.getText();
	},
	//edit comment Callback
	editCallback: function(form, value) {
		id = form.getAttribute('id');
		if(value != '')
		{
			Comment.Data[id] = value;
		}
		return 'value=' + encodeURIComponent(value); 
	},
	//edit comment onComplete
	editOnComplete: function(transport, element) {
		commentid = element.up('div.comment').readAttribute('commentid');
		if(typeof(transport) != 'undefined')
		{
			$('textilized'+commentid).update(transport.responseText);
			$('tobeedited'+commentid).update(Comment.Data[commentid]);
		}
		$('textilized'+commentid).show();
		element.hide();
	}, 
	//remove comment
	remove: function(event) {
		comment = $(this);
		comment.up('div.comment').blindUp();
		mediaid = $F('media_id');
		commentid = comment.up('div.comment').readAttribute('commentid');
		var url = '/_ajax/comments/remove.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: 'id='+mediaid+'&comment_id='+commentid,
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText == 'KO')
		  			{
		  				messageBox('There was an error while removing your comment.');
		  			}
		  		}
			}
		);
		Event.stop(event);
	},
	//form
	addForm: function(event) {
		form = $(this);
		form.select('img.spinner').invoke('show'); 
		Comment.add(form.serialize(), form);
		form.disable();
		Event.stop(event);
	},
	//mouse over comment
	mouseOver: function(event) {
		if($(this).down('.editcomment'))
			$(this).down('.editcomment').show();
		if($(this).down('.removecomment'))
			$(this).down('.removecomment').show();
	},
	//mouse out comment
	mouseOut: function(event) {
		if($(this).down('.editcomment'))
			$(this).down('.editcomment').hide();
		if($(this).down('.removecomment'))
			$(this).down('.removecomment').hide();
	},
	//toogle subscribe
	subscribeToggle: function(event) {
		$('comment_subscribe').blur();
		$('comment_subscribe').toggleClassName('on');
		Comment.subscribeUpdate();
		var url = '/_ajax/comments/subscribe/toggle.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: 'media_id='+$F('media_id'),
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText == 'KO')
		  			{
		  				messageBox('There was an error while toggling subscription to comments.');
		  			}
		  		}
			}
		);
		Event.stop(event);
	},
	//update innerHTML
	subscribeUpdate: function() {
		if($('comment_subscribe').hasClassName('on'))
		{
 			$('comment_subscribe').update('Unsubscribe');
		}
		else
		{
 			$('comment_subscribe').update('Subscribe');
		}
	},
	//on load
	setEventObserver: function(event) {
		$$('a.removecomment').invoke('observe', 'click', Comment.remove);
		$$('a.removecomment').invoke('hide');
		$$('a.editcomment').invoke('observe', 'click', Comment.edit);
		$$('a.editcomment').invoke('hide');
		$$('.comment').invoke('observe', 'mouseover', Comment.mouseOver);
		$$('.comment').invoke('observe', 'mouseout', Comment.mouseOut);
		if($('comment_subscribe'))
			$('comment_subscribe').observe('click', Comment.subscribeToggle);
		if($('frmAddComment'))
			Event.observe('frmAddComment', 'submit', Comment.addForm);
	}
}

var FlagInappropriate = {
	//flag
	add: function(pars, form) {
		var url = '/_ajax/offense/flag.php';
		new Ajax.Request(
			url,
			{
				method: 'post',
				parameters: pars,
		  		onSuccess: function(data)
		  		{
		  			if(typeof(form) != 'undefined') 
		  			{
						form.select('img.spinner').invoke('hide'); 
		  				form.enable();
		  				form.focusFirstElement();
					}
					box = $('flag-inappropriate').down('.drop-down-box'); 
					if(box)
					{
						errorbox = box.down('.ajax-error');
			  			if(data.responseText == 'OK')
			  			{
							box.update(new Element('p').update("Thank you for flagging this content. An administrator will review this submission within 24-48 hours. <a href='#' onclick='FlagInappropriate.closeBox(); return false;'>Close</a>"));
						}
						else if(data.responseText == 'KO')
						{
							errorbox.update(new Element('p').update("There was an error while flagging."));
							errorbox.show();
							// Refresh captcha
							Recaptcha.reload();
						}
						else
						{
							errorbox.update(new Element('p').update(data.responseText));
							errorbox.show();
							// Refresh capthca
							Recaptcha.reload();
						}
					}
		  		}
			}
		);
	},
	//close flag box
	closeBox: function(event) {
		SubMenu.hide('flag-inappropriate'); 
		if(typeof(event) != 'undefined')
			Event.stop(event);
	},
	//form
	addForm: function(event) {
		form = $(this);
		form.select('img.spinner').invoke('show'); 
		FlagInappropriate.add(form.serialize(), form);
		form.disable();
		Event.stop(event);
	},
	//on load
	setEventObserver: function() {
		if($('flagInappropriateLink'))
			$('flagInappropriateLink').replace($('flagInappropriateLink').innerHTML);
		if($('frmFlagInappropriate'))
			Event.observe('frmFlagInappropriate', 'submit', FlagInappropriate.addForm);
	}
}

var Group = {
	//remove from group
	remove: function(event) {
		group = $(this);
		groupId = group.readAttribute('groupid');
		groupName = group.up('li').down('a.group').innerHTML;
		mediaId = group.readAttribute('mediaid');
		group.up('li').hide();
		var url = '/_ajax/groups/remove.php';
		new Ajax.Request(url, 
			{
		  		method: 'get',
		  		parameters: 'group='+groupId+'&id='+mediaId,
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText == 'KO')
		  			{
		  				messageBox('There was an error while removing from group.');
		  			}
		  			else
		  			{
		  				$('frmAddGroups').select('select').first().insert(new Element('option', {value: groupId}).update(groupName));
		  			}
		  		}
			}
		);
		Event.stop(event);
	},
	//add to group
	add: function(pars, form) {
		var url = '/_ajax/groups/add.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
	  		onSuccess: function(data) {
	  			if(typeof(form) != 'undefined' && $('groups')) {
						selectbox = form.select('select').first();
		  			$$('#groups .not_in_any_groups').invoke('hide');
		  			$('groups').insert(data.responseText);
					  $(selectbox.options[selectbox.selectedIndex]).remove();
					  form.select('img.spinner').invoke('hide'); 
					  form.reset();
	  				form.enable();
					  Group.setEventObserver();
					}
		    }
			}
		);
	},
	//form
	addForm: function(event) {
		Event.stop(event);
		form = $(this);
		selectbox = form.select('select').first();
		if(selectbox.getValue() != '')
		{
			form.select('img.spinner').invoke('show'); 
			Group.add(form.serialize(), form);
			form.disable();
		}
		else
		{
			alert('Please select a group to add to.');
			selectbox.focus();
		}
	},
	//open add groups form
	toggleAddGroups: function(event) {
		if($('openAddGroups'))
			$('openAddGroups').toggle();
		if($('frmAddGroups'))
		{
			$('frmAddGroups').toggle();
		}
		Event.stop(event);
	},
	//on load
	setEventObserver: function(event) {
		$$('a.removegroup').invoke('observe', 'click', Group.remove);
		Group.toggleAddGroups(event);
		if($('openAddGroups'))
			$('openAddGroups').observe('click', Group.toggleAddGroups);
		if($('frmAddGroups'))
			Event.observe('frmAddGroups', 'submit', Group.addForm);
	}
}

var ExperienceCategory = {
	//remove from group
	remove: function(event) {
		category = $(this);
		categoryId = category.readAttribute('categoryid');
		categoryName = category.up('li').down('a.category').innerHTML;
		fileId = category.readAttribute('fileid');
		category.up('li').hide();
		var url = '/_ajax/experience_categories/remove.php';
		new Ajax.Request(url, 
			{
		  		method: 'get',
		  		parameters: 'category='+categoryId+'&id='+fileId,
		  		onSuccess: function(data)
		  		{
		  			if(data.responseText == 'KO')
		  			{
		  				messageBox('There was an error while removing from category.');
		  			}
		  			else
		  			{
		  				$('frmAddCategories').select('select').first().insert(new Element('option', {value: categoryId}).update(categoryName));
		  			}
		  		}
			}
		);
		Event.stop(event);
	},
	//add to group
	add: function(pars, form) {
		var url = '/_ajax/experience_categories/add.php';
		new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,
	  		onSuccess: function(data) {
	  			if(typeof(form) != 'undefined' && $('categories')) {
						selectbox = form.select('select').first();
		  			$$('#categories .not_in_any_categories').invoke('hide');
		  			$('categories').insert(data.responseText);
					  $(selectbox.options[selectbox.selectedIndex]).remove();
					  form.select('img.spinner').invoke('hide'); 
					  form.reset();
	  				form.enable();
					  ExperienceCategory.setEventObserver();
					}
		    }
			}
		);
	},
	//form
	addForm: function(event) {
		Event.stop(event);
		form = $(this);
		selectbox = form.select('select').first();
		if(selectbox.getValue() != '')
		{
			form.select('img.spinner').invoke('show'); 
			ExperienceCategory.add(form.serialize(), form);
			form.disable();
		}
		else
		{
			alert('Please select an experience to add.');
			selectbox.focus();
		}
	},
	//open add groups form
	toggleAddCategories: function(event) {
		if($('openAddCategories'))
			$('openAddCategories').toggle();
		if($('frmAddCategories'))
		{
			$('frmAddCategories').toggle();
		}
		Event.stop(event);
	},
	//on load
	setEventObserver: function(event) {
		$$('a.removecategory').invoke('observe', 'click', ExperienceCategory.remove);
		ExperienceCategory.toggleAddCategories(event);
		if($('openAddCategories'))
			$('openAddCategories').observe('click', ExperienceCategory.toggleAddCategories);
		if($('frmAddCategories'))
			Event.observe('frmAddCategories', 'submit', ExperienceCategory.addForm);
	}
}

var InPlaceEdit = {
	a: [],
	callback: function(form, value) {
		id = form.getAttribute('id').replace('-inplaceeditor','');
		if(value != '') InPlaceEdit.a[id + '_temp'] = value;
		mediaid = $(id).getAttribute('mediaid');
		if(window.event) Event.stop(window.event);
		return 'media_id=' + escape(mediaid) + '&value=' + escape(value);
	},
	init: function()
	{
		if($('media_title'))
		{
			InPlaceEdit.a['media_title'] = new Ajax.InPlaceEditor('media_title', '/_ajax/media/title/edit.php', {
				okControl: 'link',
				okText: 'Save',
				callback: InPlaceEdit.callback
			});
		}
		
		if($('media_description'))
		{
			Object.extend(Ajax.InPlaceEditor.prototype, {
				loadExternalText: function() {
					var text = this.element.innerHTML.replace(/<br\/?>/gim,"\n").replace("&nbsp;", " ").stripTags().replace(/^\s+|\s+$/g,"").replace(/\t/g, "");
					this._controls.editor.value = text;
			        this._controls.editor.disabled = false;
			        this.postProcessEditField();
				}
			});
			InPlaceEdit.a['media_description'] = new Ajax.InPlaceEditor('media_description', '/_ajax/media/description/edit.php', {
				okControl: 'link',
				okText: 'Save',
				loadTextURL: '#',
				loadingText: '',
				rows: 4,
				callback: InPlaceEdit.callback,
				onEnterEditMode: function(a) {
					$('media_description_textilize').hide();
					CustomScrollBar.hide('media_description_textilize');
				},
				onLeaveEditMode: function() { 
					$('media_description').hide();
					if(InPlaceEdit.a['media_description_temp'] != $('media_description').innerHTML) {
						$('media_description_textilize').update($('media_description').innerHTML + "<br/>");
						$('media_description').innerText = InPlaceEdit.a['media_description_temp'];
					}
					$('media_description_textilize').setStyle({ backgroundColor: '#ffffff' });
					$('media_description_textilize').show();
					CustomScrollBar.refresh('media_description_textilize');
					CustomScrollBar.show('media_description_textilize');
					if(window.event) Event.stop(window.event);
					return false;
				}			
			});
		
			$('media_description_textilize').up('.inplaceedit_wrapper').observe('mouseover', function(event){
				if(Element.hasPosition(this, Event.pointerX(event), Event.pointerY(event)))
				{
					$('media_description_textilize').setStyle({ backgroundColor: 'rgb(255, 255, 153)' });
					$('media_description_textilize').writeAttribute('title', 'Click to edit');
				}
			});
			$('media_description_textilize').up('.inplaceedit_wrapper').observe('mouseout', function(event){
				if(!Element.hasPosition(this, Event.pointerX(event), Event.pointerY(event)))
				{
					new Effect.Highlight('media_description_textilize', {endcolor: '#ffffff', restorecolor: '#ffffff'});
				} 
			});
			$('media_description_textilize').observe('click', function(event){
				try{
					InPlaceEdit.a['media_description'].enterEditMode('click');
				}catch(e){};
			});
			
			InPlaceEdit.a['media_description_temp'] = $('media_description').innerHTML;
		}

		Element.addMethods({
		    hasPosition : function(element, x, y){
		        element = $(element);
		        this.topleft = Element.cumulativeOffset(element);
		        this.bottomright = [
		            this.topleft[0] + element.offsetWidth,
		            this.topleft[1] + element.offsetHeight,
		        ];
		        return (y >= this.topleft[1] &&
		            y <  this.bottomright[1] &&
		            x >= this.topleft[0] &&
		            x <  this.bottomright[0]);
		    }
		});

	}
}
