var MainPhotoLoader = Class.create({
	label: null,
	helperPath: null,
	objectPath: null,
	position: null,
	title: null,
	limit: null,

	initialize: function(label, helperPath, objectPath, position, limit) {
		this.label = label;
		this.helperPath = helperPath;
		this.objectPath = objectPath;
		this.position = position;
		this.limit = limit;

		var _this = this;
		$$('#'+this.label+' a[direction]').each(function(item){
			item.observe('click', _this.update.bindAsEventListener(_this));
		});

	},

	timeraction: function()
	{
		var _this = this;
		$$('#'+this.label+' a[direction]').each(function(item){
			if (item.getAttribute('direction') == 'next')
				_this.scroll(item);
		});
	},

	update: function(event)
	{
		event.preventDefault();
		return this.scroll(Event.element(event));
	},

	scroll: function(el)
	{
		var offset = el.getAttribute('direction')== 'next' ? (parseInt(this.position) + 1) : (parseInt(this.position) - 1);

		if (parseInt(offset) < 0)
			offset = this.limit - 1;
		else if (offset >= this.limit)
			offset = 0;

		return this.request(offset);
	},

	request: function(offset)
	{
		var oldPosition = this.position;
		this.position = offset;
		// REWRITE_DISABLED
		//var url =  this.helperPath+'&offset='+this.position;
		// REWRITE_ENABLED
		var url =  this.helperPath+this.position;

		var _this = this;
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(result) {

		  	data = result.responseText.evalJSON();
			if (data && data.length) {
				data.each(function(s, i) {
					if (!i) {
						// REWRITE_DISABLED
/*						$(_this.label+'ImgLnk'+i).setAttribute('href', _this.objectPath + '&id=' + data[i].id);
						$(_this.label+'Lnk'+i).setAttribute('href', _this.objectPath + '&id=' + data[i].id);*/
						// REWRITE_ENABLED
						$(_this.label+'ImgLnk'+i).setAttribute('href', _this.objectPath +  data[i].id);
						$(_this.label+'Lnk'+i).setAttribute('href', _this.objectPath + data[i].id);

						$(_this.label+'Lnk'+i).update(data[i].title);
						$(_this.label+'Img'+i).setAttribute('src', data[i].preview1);
					} else if (i==1) {
						$(_this.label+'ImgLnk'+i).setAttribute('href', _this.objectPath +  data[i].id);
						$(_this.label+'Img'+i).setAttribute('src', data[i].preview2);
					} else if (i==2) {
						$(_this.label+'ImgLnk'+i).setAttribute('href', _this.objectPath +  data[i].id);
						$(_this.label+'Img'+i).setAttribute('src', data[i].preview2);
					}

					$(_this.label+'Img'+i).setAttribute('alt', data[i].title);
					$(_this.label+'Img'+i).setAttribute('title', data[i].title);
				});

			} else {
				_this.position = oldPosition;
			}
		  },

		  onComplete: function(result){
		  	//error
		  	//alert('error: '+result.responseText);
		  }
		});
	}
});
