function flagInappropriate(userId, collectionId, itemId)
{
	$('li_flag_inappropriate_' + itemId).disable = true;
	authenticAjaxRequest(restfulItemUrl(userId, collectionId, itemId) + "/inappropriate_flags", {method:'post', parameters: {item_id: itemId}});
}

adjustInterestSlider = function(item_url){
	s = new Control.Slider($$('.interestKnob')[0], $$('.interestSlider')[0], {
	  		range: $R(0,100),
			  sliderValue: parseInt($$('.interestKnob')[0].style.left)*100/148,
				onSlide: function(value){
					$$('.otherInterestMsg').first().innerHTML = TrimPath.processDOMTemplate('user_interest_div', {rating: parseInt(value)});
				},
			  onChange: function(value){
			    var old_value = s.options.sliderValue;
			    new authenticAjaxRequest(item_url + '/rate', {
			      method: 'post',
						parameters: {rating: value},
						onSuccess: function(transport){
							var result = transport.responseText.evalJSON();
							s.setValueWithoutCallbacks(result.rating);
							$$('.otherInterestMsg').first().innerHTML = TrimPath.processDOMTemplate('interest_div', result);
						},
			      onFailure: function(){
			      	s.setValueWithoutCallbacks(old_value);
							alert('an error occured while adding your interest value, please try again');
			      }
			    })
			  } 
			});
}

var Item = {
  getShowItem: function(){
    var item = {};
    item.id = parseInt($('item_id').innerHTML);
    item.collection_id = parseInt($('collection_id').innerHTML);
    item.user_id = parseInt($('user_id').innerHTML);
    item.name = $('name').innerHTML;
    item.description = $('item_description').innerHTML;
    item.item_type_id = parseInt($('item_type_id').innerHTML);
    item.item_type_name = $('item_type_name').innerHTML;
    item.tags = $$('#itemTags a').collect(function(a){return a.innerHTML});
		item.rating = $$('.ownerRatingValue').first().childElements().first().style.width.split('%').first();
    return item;
  },
  editItem: function(){
    var item = Item.getShowItem();
    var editForm = $('itemEdit').update($('item_edit_create_controls').innerHTML); 
    editForm.select('.newItem_Cancel')[0].href="javascript:Item.cancelEditItem();"
    editForm.select('.newItem_Done')[0].href="javascript:Item.updateItem();"
    var localImageForm = editForm.select('form')[0];
    var remoteImageForm = editForm.select('form')[1];
    localImageForm.select('a')[0].observe('click', function(event){localImageForm.hide();remoteImageForm.show();});
    remoteImageForm.select('a')[0].observe('click', function(event){remoteImageForm.hide();localImageForm.show();});
    editForm.select('.item_type_id')[0].value = item.item_type_id;
    editForm.select('.name')[0].value = item.name;
    var d = editForm.select('.description')[0]; 
    d.innerHTML = item.description;
    d.observe('keyup', function(){d.value = d.value.substring(0,500);});
    editForm.select('.tags')[0].value = item.tags.join();
    editForm.show();
    $('itemShow').hide();
		ListItems.Rating.showItemRating(editForm, item.rating);
  },
  cancelEditItem: function(){
    $('itemShow').show();
    $('itemEdit').hide();
  },
  updateItem: function(){
    var container = $('itemEdit');
    var localImageForm = container.select('form')[0];  //local image form
    var remoteImageForm = container.select('form')[1];  //remote image form    
    var localImageForm = container.select('form')[0];  //image form
    var errorPlaceHolder = container.select('.item_errors')[0];
    if((localImageForm.visible() && !ItemValidations.validateImageForm(localImageForm, errorPlaceHolder)) ||
      (remoteImageForm.visible() && !ItemValidations.validateImageForm(remoteImageForm, errorPlaceHolder, 'item[remote_image]')))
  		return;
    var params = ListItems.serializeItem(container) + '&in_show_page=true';
    //disable form buttons
    [container.select('.newItem_Done')[0],
     container.select('.newItem_Cancel')[0]].each(function(a){
       HTMLHelper.enableAnchor(a, false);
     });
    var updateUrl = restfulItemUrl($('user_id').innerHTML, $('collection_id').innerHTML, $('item_id').innerHTML);
    ItemValidations.clearError(errorPlaceHolder);
    new Ajax.Request(updateUrl, {
        evalJS: true,
        method: 'put',
        parameters: params,
        onSuccess: function(){
          if(remoteImageForm.visible())
            Item.setRemotePic(remoteImageForm,updateUrl);
          else
            ListItems.uploadPic(localImageForm, updateUrl);
        },
        onComplete: function(){
          [container.select('.newItem_Done')[0],
           container.select('.newItem_Cancel')[0]].each(function(a){
             HTMLHelper.enableAnchor(a, true);
           });      
        }
    });
  },
  deleteItem: function(){
  	if(confirm('Are you sure?')){
  		$('item_delete').style.display = 'none';
  		new Ajax.Request(restfulItemUrl($('user_id').innerHTML, $('collection_id').innerHTML, $('item_id').innerHTML), {
  		    method: 'delete',
  			  parameters: {redirect: true}
  		});
  	}	
  },
  setRemotePic: function(remotePicForm, url){
    if($F(remotePicForm["item[remote_image]"]) != ""){
      remotePicForm.setAttribute("action", url);
      remotePicForm.submit();
    }
  },
  initMoveItem: function(){
    $('move_to_collection_id').value = $('collection_id').innerHTML;
    $('item_move_container').show(); 
  },
  cancelMoveItem: function(){
    $('item_move_container').hide();
  },
  moveItem: function(){
    if($('collection_id').innerHTML == $('move_to_collection_id').value){
      alert('Item already in collection');      
    }
    else{
	    var params  = 'item[collection_id]=' + $('move_to_collection_id').value +'&redirect_to_item_page=true';
      $('item_move_container').hide();
      new Ajax.Request(restfulItemUrl($('user_id').innerHTML, $('collection_id').innerHTML, $('item_id').innerHTML), {
        method: 'put',
        parameters: params});
    }
  }
}

var ListItems = {
	Rating: {
		_clearStars: function(){
			var dimmedImgPath = '/images/graphics/heartTransBig.gif';
			var opaqueImgPath = '/images/graphics/heartOpaqueBig.gif';
			var starsSelectedNum = this.parentNode.select('input').first().value / 20;
			var ratingLinks = this.up().select('a');
			for(var i=0 ; i<starsSelectedNum ; i++){
				ratingLinks[i].select('img').first().src = opaqueImgPath;
			}
			for(var i=starsSelectedNum ; i<5 ; i++){
				ratingLinks[i].select('img').first().src = dimmedImgPath;
			}
		},
		_showStars: function(){
			var dimmedImgPath = '/images/graphics/heartTransBig.gif';
			var opaqueImgPath = '/images/graphics/heartOpaqueBig.gif';
		  var imgPath = '/images/graphics/heartOpaqueSmall.png';
		  var ratingLinks = this.up().select('a');
		  var starsSelectedNum = this.previousSiblings().length;
		  for(var i=0 ; i<starsSelectedNum ; i++){
				ratingLinks[i].select('img').first().src = opaqueImgPath;
			}
			for(var i=starsSelectedNum ; i<5 ; i++){
				ratingLinks[i].select('img').first().src = dimmedImgPath;
			}
		},
		_saveRating: function(){
			this.parentNode.select('input').first().value = this.previousSiblings().length * 20;
		},
		showItemRating: function(Form, rating){
			//Save rating value in hidden field for using it in serialization of update
			Form.select('.newItem_rating input').first().value = rating;
			
			//Show old rating value
			var starsSelectedNum = (rating / 20);
			var ratingLinks = Form.select('.newItem_rating a');
			for(var i=0 ; i<starsSelectedNum ; i++){
				ratingLinks[i].select('img').first().src = '/images/graphics/heartOpaqueBig.gif';
			}
			
			//Prepare rating functionality
	    for(var i=0 ; i<ratingLinks.length ; i++){
	      ratingLinks[i].observe('mouseover', this._showStars);
	      ratingLinks[i].observe('mouseout', this._clearStars);
	      ratingLinks[i].observe('click', this._saveRating);
	    }
		}	
	},
  getShowItem: function(itemId){
    var container = $('item_'+itemId+'_show');
    var item = {};
    item.name = container.select('.name')[0].innerHTML;
    item.description = container.select('.description')[0].innerHTML;
    item.item_type_id = parseInt(container.select('.item_type_id')[0].innerHTML);
    item.comments_count = parseInt(container.select('.comments_count')[0].innerHTML);
    item.tags = container.select('.tags a').collect(function(a){return a.innerHTML});
		item.rating = container.select('.itemUserRating').first().childElements().first().style.width.split('%').first();
    return item;
  },	
  getEditItem: function(itemId){
    var container = $('item_'+itemId+'_edit');
    var item = {};
    item.name = container.select('.name')[0].value;
    item.description = container.select('.description')[0].innerHTML;
    item.item_type_id = parseInt(container.select('.item_type_id')[0].value);
    item.tags = container.select('.tags')[0].value.split();
    return item;
  },
  serializeItem: function(container){
		var params = [container.select('.name')[0], container.select('.description')[0],
                  container.select('.item_type_id')[0], container.select('.tags')[0]]
		if(parseInt(container.select('.newItem_rating input').first().value) != 0)
			params.push(container.select('.newItem_rating input').first());
    
		return params.map(function(i){return i.serialize(true);}).join('&');
  },
  editItem: function(userId, collectionId, itemId){
    var item = ListItems.getShowItem(itemId);
    //init the edit form
    var editForm = $('item_'+itemId+'_edit_controls').update($('item_edit_create_controls').innerHTML);
    editForm.select('.newItem_Cancel')[0].href="javascript:ListItems.cancelEditItem("+itemId+");"
    editForm.select('.newItem_Done')[0].href="javascript:ListItems.updateItem("+userId+","+collectionId+","+itemId+");"
    var localImageForm = editForm.select('form')[0];
    var remoteImageForm = editForm.select('form')[1];
    localImageForm.select('a')[0].observe('click', function(event){localImageForm.hide();remoteImageForm.show();});
    remoteImageForm.select('a')[0].observe('click', function(event){remoteImageForm.hide();localImageForm.show();});
    editForm.select('.item_type_id')[0].value = item.item_type_id;
    editForm.select('.name')[0].value = item.name;
    var d = editForm.select('.description')[0]; 
    d.innerHTML = item.description;
    d.observe('keyup', function(){d.value = d.value.substring(0,500);});
    editForm.select('.tags')[0].value = item.tags.join();
    $('item_'+itemId+'_show').hide();
    $('item_'+itemId+'_edit').show();
		this.Rating.showItemRating(editForm, item.rating);
  },
  cancelEditItem: function(itemId){
    $('item_'+itemId+'_edit').hide();
    $('item_'+itemId+'_edit_controls').update('');
    $('item_'+itemId+'_show').show();
  },
  updateItem: function(userId, collectionId, itemId){
    var container = $('item_'+itemId+'_edit');    
    var localImageForm = container.select('form')[0];  //local image form
    var remoteImageForm = container.select('form')[1];  //remote image form
    var errorPlaceHolder = container.select('.item_errors')[0];
    if((localImageForm.visible() && !ItemValidations.validateImageForm(localImageForm, errorPlaceHolder)) ||
       (remoteImageForm.visible() && !ItemValidations.validateImageForm(remoteImageForm, errorPlaceHolder, 'item[remote_image]')))
  		return;
    var params = ListItems.serializeItem(container);
    //disable form buttons
    [container.select('.newItem_Done')[0],
     container.select('.newItem_Cancel')[0]].each(function(a){
       HTMLHelper.enableAnchor(a, false);
     });
    var updateUrl = restfulItemUrl(userId, collectionId, itemId);
    ItemValidations.clearError(errorPlaceHolder);
    new Ajax.Request(updateUrl, {
        evalJS: true,
        method: 'put',
        parameters: params,
        onSuccess: function(){
          if(remoteImageForm.visible())
            Item.setRemotePic(remoteImageForm, updateUrl);
          else
            ListItems.uploadPic(localImageForm, updateUrl);            
        },
        onComplete: function(){
          [container.select('.newItem_Done')[0],
           container.select('.newItem_Cancel')[0]].each(function(a){
             HTMLHelper.enableAnchor(a, true);
           });
        }
    });
  },
  newItem: function(userId, collectionId){
    var newForm = $('new_item_'+collectionId).update($('item_edit_create_controls').innerHTML);
    newForm.select('.newItem_Cancel')[0].observe('click', function(event){ListItems.cancelNewItem(collectionId);});
    newForm.select('.newItem_Done')[0].observe('click', function(event){ListItems.createItem(userId,collectionId);});
    var localImageForm = newForm.select('form')[0];
    var remoteImageForm = newForm.select('form')[1];  //local image form
    localImageForm.select('a')[0].observe('click', function(event){localImageForm.hide();remoteImageForm.show();});
    remoteImageForm.select('a')[0].observe('click', function(event){remoteImageForm.hide();localImageForm.show();});
    newForm.show();
		this.Rating.showItemRating(newForm, 0);
  },
  cancelNewItem: function(collectionId){
    $('new_item_'+collectionId).hide();
    $('new_item_'+collectionId).update('');
  },
  createItem: function(userId, collectionId){
    var container = $('new_item_'+collectionId);
    var localImageForm = container.select('form')[0];  //local image form
    var remoteImageForm = container.select('form')[1];  //remote image form
    var errorPlaceHolder = container.select('.item_errors')[0];
    if((localImageForm.visible() && !ItemValidations.validateImageForm(localImageForm, errorPlaceHolder)) ||
       (remoteImageForm.visible() && !ItemValidations.validateImageForm(remoteImageForm, errorPlaceHolder, 'item[remote_image]')))
  		return;
    var params = ListItems.serializeItem(container);
    //disable form buttons
    [container.select('.newItem_Done')[0],
     container.select('.newItem_Cancel')[0]].each(function(a){
       HTMLHelper.enableAnchor(a, false);
     });
    ItemValidations.clearError(errorPlaceHolder);
    new Ajax.Request(restfulItemUrl(userId, collectionId, ""), {
        evalJS: true,
        method: 'post',
        parameters: params,
        onSuccess: function(transport){
            var location = "" + transport.getHeader('Location');
            var newItemId = location.substring(location.lastIndexOf('/') + 1);
            var updateUrl = restfulItemUrl(userId, collectionId, newItemId);
            if(remoteImageForm.visible())
              Item.setRemotePic(remoteImageForm, updateUrl);
            else
              ListItems.uploadPic(localImageForm, updateUrl);
        },
        onComplete: function(){
          [container.select('.newItem_Done')[0],
           container.select('.newItem_Cancel')[0]].each(function(a){
             HTMLHelper.enableAnchor(a, true);
           });
        }
    });
  },
  uploadPic: function(uploadForm, url){
    if ($F(uploadForm["item_image"]) != "") {
        uploadForm.setAttribute("action", url);
        uploadForm.submit();
    }
  },
  deleteItem: function(userId, collectionId, itemId, redirect){
  	if(confirm('Are you sure?')){
  		$('a_delete_item_' + itemId).style.display = 'none';
  		new Ajax.Request(restfulItemUrl(userId, collectionId, itemId), {
  		    method: 'delete',
  			parameters: {redirect: redirect}
  		});
  	}	
  }
}

var Comments = {
  newCommentJSTId: 'newCommentJST',
  newCommentJST: null,
  addComment: function(userId, collectionId, itemId){
    
    //TODO handle the case if no comments are visible initially
    var newComment = $('itemAddCommentText'); 
    if(newComment.value.gsub(/\s/,'').length == 0){
      alert("You can't add an empty comment !");      
    }
    else{
      authenticAjaxRequest(restfulItemUrl(userId, collectionId, itemId) + "/comments",
        {method:'post', parameters: {comment_text: newComment.value}, onSuccess: function(transport){
          var comment = eval('('+transport.responseText+')');
          if (Comments.newCommentJST == null) {
            Comments.newCommentJST = TrimPath.parseDOMTemplate(Comments.newCommentJSTId);
          }
          comment.ownerShipClass = comment.is_owner ? 'ownerComment' : ''
          comment.item_id = itemId;
          comment.item_collection_id = collectionId;
          comment.item_user_id = userId;
          var c = Comments.newCommentJST.process(comment);
          var csContainer = $('itemComments');
          csContainer.show(); //in case it was hidden when the comment being added now is the first comment
          csContainer.insert(c);
          newComment.value = '';
          Effect.SlideDown('comment_'+comment.id);
        }});
    }  
  },
  deleteComment: function(userId, collectionId, itemId, commentId){
    if(confirm('Are you sure you want to delete this comment?')){
      authenticAjaxRequest(restfulItemUrl(userId, collectionId, itemId) + "/comments/" + commentId,
      {method:'delete', 
       onSuccess: function(transport){
         Effect.Fade('comment_'+commentId, {afterFinish: function(){$('comment_' + commentId).remove();}});
       }
       });
    }  
  }
}  

var CollectionItemsScroller = {
  totalItemsCount: 0,
  windowItemsCount: 0,
  readyItemsCount:0,
  lastItemIndex:1,
  itemWidth: 0,
  itemsContainerWidth: 0,
  itemsWindowWidth: 0,
  prevId: '',
  nextId:'',
  contentId:'',
  itemsUrl: '',
  disabled: false,
  init: function(itemWidth, windowItemsCount, totalItemsCount, contentId,nextId, prevId, itemsUrl){
	if(totalItemsCount < windowItemsCount){
      $(prevId+'_link').hide();
      $(nextId+'_link').hide();
      return;
    }
    CollectionItemsScroller.totalItemsCount = totalItemsCount;
    CollectionItemsScroller.windowItemsCount = windowItemsCount;
    CollectionItemsScroller.readyItemsCount = totalItemsCount <= windowItemsCount ? totalItemsCount : windowItemsCount;
    CollectionItemsScroller.lastItemIndex = CollectionItemsScroller.readyItemsCount;
    CollectionItemsScroller.itemWidth = itemWidth;
    CollectionItemsScroller.itemsContainerWidth = totalItemsCount * itemWidth;
    CollectionItemsScroller.itemsWindowWidth = windowItemsCount * itemWidth;
    CollectionItemsScroller.prevId = prevId;
    CollectionItemsScroller.nextId = nextId;
    CollectionItemsScroller.contentId = contentId;
    CollectionItemsScroller.itemsUrl = itemsUrl;
    $('itemCollectionContent').style.width = CollectionItemsScroller.itemsContainerWidth+'px';
    CollectionItemsScroller.updateNavigationButtons();
  },

  nextItems: function(count){
    var newLastIndex = CollectionItemsScroller.lastItemIndex + count;
    if(CollectionItemsScroller.totalItemsCount <= CollectionItemsScroller.windowItemsCount)
      return;
    if(CollectionItemsScroller.readyItemsCount < CollectionItemsScroller.totalItemsCount && newLastIndex > CollectionItemsScroller.readyItemsCount){
      var page = Math.ceil(newLastIndex / CollectionItemsScroller.windowItemsCount);
      var url = CollectionItemsScroller.itemsUrl +"?page="+page+"&per_page="+CollectionItemsScroller.windowItemsCount;
      new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
          var items = eval('('+transport.responseText+')');
          CollectionItemsScroller.readyItemsCount += items.length;
          CollectionItemsScroller.addItems(items);
          CollectionItemsScroller.scrollNextItems(count);
        }
      });
    }
    else {
      CollectionItemsScroller.scrollNextItems(count);
    }
  },
  scrollNextItems: function(count){
    var leftItemsCount = CollectionItemsScroller.totalItemsCount - CollectionItemsScroller.lastItemIndex;
    if(CollectionItemsScroller.disabled || CollectionItemsScroller.totalItemsCount <= CollectionItemsScroller.windowItemsCount || leftItemsCount == 0)
      return;
    var toMoveItemsCount = leftItemsCount > count ? count : leftItemsCount;
    CollectionItemsScroller.lastItemIndex += toMoveItemsCount;
    CollectionItemsScroller.updateLeftMargin(-toMoveItemsCount * CollectionItemsScroller.itemWidth);
    CollectionItemsScroller.updateNavigationButtons();
  },
  scrollPreviousItems: function(count){
    var leftItemsCount = CollectionItemsScroller.lastItemIndex > CollectionItemsScroller.windowItemsCount ? (CollectionItemsScroller.lastItemIndex - CollectionItemsScroller.windowItemsCount) : 0;
    if(CollectionItemsScroller.disabled || leftItemsCount == 0)
      return;
    var toMoveItemsCount = leftItemsCount > count ? count : leftItemsCount;
    CollectionItemsScroller.lastItemIndex -= toMoveItemsCount;  
    CollectionItemsScroller.updateLeftMargin(toMoveItemsCount * CollectionItemsScroller.itemWidth);
    CollectionItemsScroller.updateNavigationButtons();
  },
  updateLeftMargin: function(step){
    var leftMargin = parseInt($('itemCollectionContent').getStyle('marginLeft'));  
    $('itemCollectionContent').morph('margin-left:'+(leftMargin+step)+'px;',{beforeStart:function(){CollectionItemsScroller.disabled=true;}, afterFinish:function(){CollectionItemsScroller.disabled=false;},transition: Effect.Transitions.sinoidal, duration: 0.5});
  },
  addItems: function(items){
    items.each(function(item){
      var img = new Element('img', { 'src': item.image});
      var a = new Element('a', {'href': item.url, 'title': item.name});
      a.insert(img);
      var div = new Element('div', { 'class': 'itemCollectionItem'});
      div.insert(a);
      $(CollectionItemsScroller.contentId).insert(div);
    });
  },
 updateNavigationButtons: function(){
    if(CollectionItemsScroller.lastItemIndex == CollectionItemsScroller.windowItemsCount)
      $$('#'+CollectionItemsScroller.prevId+' a')[0].hide();
    if(CollectionItemsScroller.lastItemIndex < CollectionItemsScroller.totalItemsCount)
      $$('#'+CollectionItemsScroller.nextId+' a')[0].show();
    if(CollectionItemsScroller.lastItemIndex > CollectionItemsScroller.windowItemsCount)
      $$('#'+CollectionItemsScroller.prevId+' a')[0].show();
    if(CollectionItemsScroller.lastItemIndex == CollectionItemsScroller.totalItemsCount)
      $$('#'+CollectionItemsScroller.nextId+' a')[0].hide();
  }
  
}