var ItemChooser = Class.create({
	
	id: null,
	actionFile: null,
	parameters: null,
	trashActionFile: null,
	reloadParameters: null,
	
	initialize: function (id,actionFile,parameters,trashActionFile) {
		this.id = id;
		this.actionFile = actionFile;
		this.parameters = parameters;
		this.trashActionFile = trashActionFile;
	},
	
	reload:function(actionFile,parameters,trashActionFile){	
		
		if (!actionFile){
			actionFile = this.actionFile;
		}
		
		if (!parameters){
			parameters = this.parameters;
		}
		
		if (!parameters.command){
			parameters.command = 'printItems';
		}
		
		if (!trashActionFile){
			trashActionFile = this.trashActionFile;
		}
		
		system.getActionManager().executeAndPutResultIntoContainer(actionFile,parameters,this.id,true);
		
		if ($('trashSectionContainer') && trashActionFile){
			system.getActionManager().executeAndPutResultIntoContainer(trashActionFile,{command: 'printTrashIcon', style: system.getCurrentStyle() },'trashSectionContainer',true);	
		}
	},
	
	executeAndReload:function(actionFile,parameters,reloadParameters,trashActionFile){
		
		if (!actionFile){
			actionFile = this.actionFile;
		}
		
		if (!parameters){
			parameters = this.parameters;
		}
		
		if (!trashActionFile){
			trashActionFile = this.trashActionFile;
		}
		
		if (!reloadParameters){
			reloadParameters = this.reloadParameters;
		}
		
		var id = this.id;
		
		new Ajax.Request(actionFile, {
			method:'post',
			parameters: parameters,
			onSuccess: function(transport) {
				if( transport.responseText!='OK' ) {
					system.getMessageManager().showMessage(transport.responseText, { color:'red' });
				}
				else {
					system.getActionManager().executeAndPutResultIntoContainer(actionFile,reloadParameters,id,true);
					
					//new Page(actionFile,reloadParameters,this.id);

					if ($('trashSectionContainer')){
						system.getActionManager().executeAndPutResultIntoContainer(trashActionFile,{command: 'printTrashIcon', style: system.getCurrentStyle() },'trashSectionContainer',true);	
					}
				}
			}
		});
	}
		
});

var ItemSlider = Class.create({
	id: null,
	pos: 25,
	inc: 70,
	originalInc: 70,
	numCallsForFastInc: 15,
	numCallsForDoubleFastInc: 40,
	currentCalls: 0,
	fastInc: 70,
	doubleFastInc: 70,
	fadeTime: 0.03,
	mouseOverLeft:false,
	mouseOverRight: false,
	leftDisabled: false,
	rightDisabled: false,
	slideshowId: 'slideshow1_',
	slideshowField: null,
	slideshowContainerId: 'slideshowContainer1_',
	slideshowContainerField: null,
	leftArrowId: 'leftArrow_',
	leftArrowField: null,
	rightArrowId: 'rightArrow_',
	rightArrowField: null,
	leftArrowImage: 'left_arrow.png',
	leftArrowImageOver: 'left_arrow_over.png',
	rightArrowImage: 'right_arrow.png',
	rightArrowImageOver: 'right_arrow_over.png',
	imagesPath: '',
	vertical: false,
	
	scrollRightLimit: 0,
	scrollLeftLimit: 0,
	
	initialize: function (id,pos,inc,leftArrow,leftArrowOver,rightArrow,rightArrowOver,vertical) {
		this.id = id;
		this.pos = pos;
		this.inc = inc;
		this.originalInc = inc;
		this.fastInc = inc;
		this.doubleFastInc = inc;
		this.slideshowField = $(this.slideshowId + this.id);
		this.slideshowContainerField = $(this.slideshowContainerId + this.id);
		
		this.leftArrowImage = leftArrow;
		this.leftArrowImageOver = leftArrowOver;
		this.rightArrowImage = rightArrow;
		this.rightArrowImageOver = rightArrowOver;
		
		this.leftArrowField = $(this.leftArrowId + this.id);
		this.rightArrowField = $(this.rightArrowId + this.id);
		this.imagesPath = "";
		this.vertical = vertical;
		
		this.calculateScrollLeftLimit();
		this.calculateScrollRightLimit();
		
		this.checkLeftDisabled();
		this.checkRightDisabled();
		
	},
	
	resetInc: function () {
		this.currentCalls = 0;
		this.inc = this.originalInc;		
	},
	
	checkFastInc: function() {
		if (this.currentCalls>this.numCallsForDoubleFastInc){
			this.inc = this.doubleFastInc;
		}
		else if (this.currentCalls>this.numCallsForFastInc){
			this.inc = this.fastInc;
		}
	},
	
	moveLeft: function (){
		//alert('offsetleft ' + this.slideshowField.offsetLeft);
		
		var limitExceeded = false;
		
		if (this.vertical){
			if (this.slideshowField.offsetTop+this.inc>=this.scrollLeftLimit){
				limitExceeded = true;
			}
		}
		else {
			if (this.slideshowField.offsetLeft+this.inc>=this.scrollLeftLimit){
				limitExceeded = true;
			}
		}
		
		
		if (!limitExceeded) {
			//this.pos += this.inc;
			if (this.vertical){
				new Effect.Move(this.slideshowField, { x: 0, y: this.inc, mode: 'relative', duration: 0.2,transition: Effect.Transitions.linear});
				//this.slideshowField.style.top = this.pos + 'px';
			}
			else {
				//this.slideshowField.style.left = this.pos + 'px';
				new Effect.Move(this.slideshowField, { x: this.inc, y: 0, mode: 'relative',duration: 0.2,transition: Effect.Transitions.linear});
			}
			this.checkRightDisabled();
			this.currentCalls++;
		}
		else {
			
			if (this.vertical){
				new Effect.Move(this.slideshowField, { x: 0, y: this.scrollLeftLimit-this.slideshowField.offsetTop, mode: 'relative', duration: 0.2, transition: Effect.Transitions.linear});
				//this.slideshowField.style.top = this.pos + 'px';
			}
			else {
				//this.slideshowField.style.left = this.pos + 'px';
				new Effect.Move(this.slideshowField, { x: this.scrollLeftLimit-this.slideshowField.offsetLeft, y: 0, mode: 'relative',duration: 0.2,transition: Effect.Transitions.linear});
			}
			
			this.disableLeftArrow();
			this.resetInc();
		}
		
		this.checkFastInc();

		/*if (this.pos){
			if (this.vertical){
				new Effect.Move(this.slideshowField, { x: 0, y: this.inc, mode: 'relative', duration: 0.2});
				//this.slideshowField.style.top = this.pos + 'px';
			}
			else {
				//this.slideshowField.style.left = this.pos + 'px';
				new Effect.Move(this.slideshowField, { x: this.inc, y: 0, mode: 'relative',duration: 0.2});
			}
		}*/		

	},
	moveRight: function (){
		//alert('offsetleft ' + this.slideshowField.offsetLeft);
		
		var limitExceeded = false;

		if (this.vertical){
			if (this.slideshowField.offsetTop-this.inc<=this.scrollRightLimit){
				limitExceeded = true;
			}
		}
		else {
			if (this.slideshowField.offsetLeft-this.inc<=this.scrollRightLimit){
				limitExceeded = true;
			}
		}
		
		if (!limitExceeded){
			//this.pos -= this.inc;
			//new Effect.Move(this.slideshowField, { x: 20, y: -30, mode: 'relative' });
			if (this.vertical) {
				new Effect.Move(this.slideshowField, { x: 0, y: -this.inc, mode: 'relative', duration: 0.2,transition: Effect.Transitions.linear});
			}
			else {
				new Effect.Move(this.slideshowField, { x: -this.inc, y: 0, mode: 'relative',duration: 0.2,transition: Effect.Transitions.linear});
			}
			
			this.checkLeftDisabled();
			this.currentCalls++;
		}
		else {
			
			if (this.vertical) {
				new Effect.Move(this.slideshowField, { x: 0, y: this.scrollRightLimit-this.slideshowField.offsetTop, mode: 'relative', duration: 0.2,transition: Effect.Transitions.linear});
			}
			else {
				new Effect.Move(this.slideshowField, { x: this.scrollRightLimit-this.slideshowField.offsetLeft, y: 0, mode: 'relative',duration: 0.2,transition: Effect.Transitions.linear});
			}
			
			//alert('disable right. Left: ' + this.slideshowField.offsetLeft + ' limit ' + this.scrollRightLimit);
			
			this.disableRightArrow();
			this.resetInc();
		}

		this.checkFastInc();

		/*if (this.pos){
			if (this.vertical){
				this.slideshowField.style.top = this.pos + 'px';
			}
			else {
				this.slideshowField.style.left = this.pos + 'px';				
			}
		}*/

	},

	checkLeftDisabled: function (){
		if (this.vertical){
			if (this.slideshowField.offsetTop<this.scrollLeftLimit) {
				this.enableLeftArrow();
			}
			else {
				this.disableLeftArrow();
			}
		}
		else {
			if (this.slideshowField.offsetLeft<this.scrollLeftLimit) {
				this.enableLeftArrow();
			}
			else {
				this.disableLeftArrow();
			}			
		}
	},

	calculateScrollRightLimit: function ()
	{
		if (this.vertical){
			this.scrollRightLimit = this.scrollLeftLimit+(this.slideshowContainerField.offsetHeight-this.slideshowField.offsetHeight);
		}
		else {
			this.scrollRightLimit = this.scrollLeftLimit+(this.slideshowContainerField.offsetWidth-this.slideshowField.offsetWidth);
			//alert('scroll right limit ' + this.scrollRightLimit);
		}
	},

	calculateScrollLeftLimit: function ()
	{
		if (this.vertical){
			this.scrollLeftLimit = this.slideshowField.offsetTop + this.pos; //this.pos; //(this.inc+20);
		}
		else {
			this.scrollLeftLimit = this.slideshowField.offsetLeft + this.pos; //this.pos; //(this.inc+20);			
		}
	},

	checkRightDisabled: function (){
		if (this.vertical){
			if (this.slideshowField.offsetTop>this.scrollRightLimit){
				this.enableRightArrow();
			}
			else {
				this.disableRightArrow();
			}
		}
		else {
			if (this.slideshowField.offsetLeft>this.scrollRightLimit){
				this.enableRightArrow();
			}
			else {
				this.disableRightArrow();
			}			
		}
	},

	enableLeftArrow: function ()
	{
		if (this.leftDisabled){
			new Effect.Appear(this.leftArrowField,this.fadeTime);
			this.leftDisabled = false;			
		}
	},

	enableRightArrow: function ()
	{
		if (this.rightDisabled){
			new Effect.Appear(this.rightArrowField,this.fadeTime);
			this.rightDisabled = false;			
		}
	},

	disableLeftArrow: function ()
	{
		//new Effect.Fade('leftArrow_' + id,fadeTime);
		this.leftDisabled = true;
	},

	disableRightArrow: function ()
	{
		//new Effect.Fade('rightArrow_' +id,fadeTime);
		this.rightDisabled = true;
	},

	overLeft: function (){
		if (!this.leftDisabled){
			this.leftArrowField.src = this.imagesPath + this.leftArrowImageOver;
			this.mouseOverLeft = true;
			var id = this.id;
			new PeriodicalExecuter(function(pe) {
				//this.moveLeft;
				itemSliderManager.getItemSlider(id).moveLeft();
				if (!itemSliderManager.getItemSlider(id).mouseOverLeft) pe.stop();
			}, 0.2);
		}
		else {
			this.checkLeftDisabled();
		}
	},

	outLeft: function (){
		this.mouseOverLeft = false;
		this.leftArrowField.src = this.imagesPath + this.leftArrowImage;
		this.resetInc();
	},

	overRight: function (){
		if (!this.rightDisabled){
			this.mouseOverRight = true;
			this.rightArrowField.src = this.imagesPath + this.rightArrowImageOver;
			var id = this.id;
			new PeriodicalExecuter(function(pe) {
				itemSliderManager.getItemSlider(id).moveRight();
				//this.moveRight;
				if (!itemSliderManager.getItemSlider(id).mouseOverRight) pe.stop();
			}, 0.2);
		}
		else {
			this.checkRightDisabled();
		}
	},

	outRight: function (){
		this.mouseOverRight = false;
		this.rightArrowField.src = this.imagesPath + this.rightArrowImage;
		this.resetInc();
	}
	
	
});


var ItemSliderManager = Class.create({
	
	itemSliders:new Array(),
	
	initialize: function () {
	},
	
	addItemSlider: function (id,pos,inc,leftArrow,leftArrowOver,rightArrow,rightArrowOver,vertical){
		this.itemSliders[id] = new ItemSlider(id,pos,inc,leftArrow,leftArrowOver,rightArrow,rightArrowOver,vertical);
	},
	
	removeItemSlider: function (id) {
		this.itemSliders[id] = null;
	},
	
	getItemSlider: function(id) {
		return this.itemSliders[id];
	}
});


var ImageEffect = Class.create({
	
	id: null,
	field: null,
	overEffectName: "",
	outEffectName: "",
	overParameters: null,
	outParameters: null,
	overEffect: null,
	outEffect: null,

	initialize: function (id,field,overEffectName,outEffectName,overParameters,outParameters) {
		this.id = id;
		this.field = field;
		this.overEffectName = overEffectName;
		this.outEffectName = outEffectName;
		this.overParameters = overParameters;
		this.outParameters = outParameters;
		
		var id = this.id;
		field.observe('mouseover',function (event) { imageEffectsManager.getImageEffect(id).applyOverEffect(); });
		field.observe('mouseout',function (event) { imageEffectsManager.getImageEffect(id).applyOutEffect(); });
		
		this.applyOutEffect();
	},
	
	applyOverEffect: function(){
		
		if (this.overEffectName=="") return;
		
		if (this.outEffect){
			this.outEffect.cancel();
		}
		
		this.overEffect =  new Effect[this.overEffectName](this.field,this.overParameters);
	},
	applyOutEffect: function() {
		
		if (this.outEffectName=="") return;
		
		if (this.overEffect){
			this.overEffect.cancel();
		}
		
		this.outEffect = new Effect[this.outEffectName](this.field,this.outParameters);
	}
	
});


var ImageEffectsManager = Class.create({
	imageEffects:new Array(),
	
	initialize: function () {
	},
	
	addImageEffect: function (id,field,overEffectName,outEffectName,overParameters,outParameters){
		this.imageEffects[id] = new ImageEffect(id,field,overEffectName,outEffectName,overParameters,outParameters);
	},
	
	removeImageEffect: function (id) {
		this.imageEffects[id] = null;
	},
	
	getImageEffect: function(id) {
		return this.imageEffects[id];
	}

});

var FileUploader = Class.create({
	id: null,
	uploader: null,
	
	initialize: function(id,uploader){
		this.id = id;
		this.uploader = uploader;
	},
	
	clearError: function(event){
		
		var errorMessage = errorManager.getError(this.id);
		if (errorMessage) {
			errorMessage.clearError();
		}		
	},
	
	uploadError: function(event) {
		
		var errorMessage = errorManager.getError(this.id);
		if (errorMessage) {
			errorMessage.addError(event.memo.error);
		}		
	},
	
	uploadWarning: function(event) {
		
		var warningMessage = errorManager.getError(this.id);
		if (warningMessage) {
			warningMessage.addError(event.memo.warning);
		}		
	},
	
	getMovie: function() {
		return this.uploader;
	}
	
});


var FileUploadersManager = Class.create({
	uploaders:new Array(),
	
	initialize: function () {
	},
	
	addUploader: function(id,uploader) {
		this.uploaders[id] = new FileUploader(id,uploader);
	},
	
	getUploader: function(id) {
		return this.uploaders[id];
	},
	
	getUploaderMovie: function(id) {
		if (this.uploaders[id]){
			return this.uploaders[id].getMovie();			
		}
		return null;
	},
	
	uploadSuccess: function (event) {
			
		if (this.uploaders[event.memo.uploaderId]){
			this.uploaders[event.memo.uploaderId].clearError(event);
			this.uploaders[event.memo.uploaderId].uploadError(event);
			this.uploaders[event.memo.uploaderId].uploadWarning(event);
		}
	},
	
	uploadError: function (event) {
		
		if (event.memo.error) {
			if (this.uploaders[event.memo.uploaderId]){
				//this.uploaders[event.memo.uploaderId].clearError(event);
				this.uploaders[event.memo.uploaderId].uploadError(event);
			}
		}
	},
	
	uploadWarning: function(event){
		if (event.memo.warning) {
			if (this.uploaders[event.memo.uploaderId]){
				//this.uploaders[event.memo.uploaderId].clearError(event);
				this.uploaders[event.memo.uploaderId].uploadWarning(event);
			}
		}
	}
	
});


var MapManager = Class.create({
	mapType: null,
	centerLatitude: 0,
	centerLongitude: 0,
	latitude: 0,
	longitude: 0,
	zoom: 14,
	name: null,
	
	initialize: function(mapType,centerLatitude,centerLongitude,latitude,longitude,zoom,name) {
		this.mapType = mapType;
		this.centerLatitude = centerLatitude;
		this.centerLongitude = centerLongitude;
		this.latitude = latitude;
		this.longitude = longitude;
		this.zoom = zoom;
		this.name = name;
	},
	

	loadMap: function() {

 		if ((typeof GBrowserIsCompatible == 'function') && GBrowserIsCompatible()) {
        	var map = new GMap2(document.getElementById("map_canvas"));
			map.setMapType(this.mapType); 


			map.setUIToDefault();
			//map.enableGoogleBar();

			var center = new GLatLng(this.centerLatitude,this.centerLongitude);
			map.setCenter(center,this.zoom);

			var markerPos = new GLatLng(this.latitude,this.longitude);
			var marker = new GMarker(markerPos);
		
			GEvent.addListener(map,"dragend",function() {
				var lanLng = map.getCenter();
				$("centerLatitude").value = lanLng.lat();
				$("centerLongitude").value = lanLng.lng();
			});
		
			GEvent.addListener(map,"zoomend",function(oldLevel,newLevel) {
				$("zoom").value = newLevel;
			});

			function getMapTypeString(mapType){
				if (mapType==G_NORMAL_MAP){
					return "G_NORMAL_MAP"; 
				}
				else if (mapType==G_SATELLITE_MAP){
					return "G_SATELLITE_MAP";
				}
				else if (mapType==G_HYBRID_MAP) {
					return "G_HYBRID_MAP";
				}								    
			};

			GEvent.addListener(map,"maptypechanged",function() {
				$("mapType").value = getMapTypeString(map.getCurrentMapType());
			});
		
		

			GEvent.addListener(marker, "dragend", function() {
				//marker.openInfoWindowHtml("Movámonos un poco...");
				var lanLng = marker.getLatLng();
				$("latitude").value = lanLng.lat();
				$("longitude").value = lanLng.lng();
			  });

			map.addOverlay(marker);

			marker.bindInfoWindowHtml(this.name);
			marker.openInfoWindowHtml(this.name);

      }
    },

	loadEditMap: function () {
		if ((typeof GBrowserIsCompatible == 'function') && GBrowserIsCompatible()) {
	        var map = new GMap2(document.getElementById("map_canvas"));
			//map.setMapType(this.mapType); 

			map.addControl(new GLargeMapControl3D());
			//map.addControl(new GScaleControl());
			//map.setUIToDefault();
			//map.removeControl();
			//map.enableGoogleBar();

			var center = new GLatLng(this.centerLatitude,this.centerLongitude);
			map.setCenter(center,this.zoom);

			var markerPos = new GLatLng(this.latitude,this.longitude);
			var marker = new GMarker(markerPos, {draggable: true});
	

			GEvent.addListener(map,"dragend",function() {
				var lanLng = map.getCenter();
				$("centerLatitude").value = lanLng.lat();
				$("centerLongitude").value = lanLng.lng();
			});
		
			GEvent.addListener(map,"zoomend",function(oldLevel,newLevel) {
				$("zoom").value = newLevel;
			});

			function getMapTypeString(mapType){
				if (mapType==G_NORMAL_MAP){
					return "G_NORMAL_MAP"; 
				}
				else if (mapType==G_SATELLITE_MAP){
					return "G_SATELLITE_MAP";
				}
				else if (mapType==G_HYBRID_MAP) {
					return "G_HYBRID_MAP";
				}								    
			};

			GEvent.addListener(map,"maptypechanged",function() {
				$("mapType").value = getMapTypeString(map.getCurrentMapType());
			});
		
		

			GEvent.addListener(marker, "dragstart", function() {
			 	map.closeInfoWindow();
			});

			GEvent.addListener(marker, "dragend", function() {
				var lanLng = marker.getLatLng();
				$("latitude").value = lanLng.lat();
				$("longitude").value = lanLng.lng();
				marker.openInfoWindowHtml(this.name);
			  });

			map.addOverlay(marker);
			marker.bindInfoWindowHtml(this.name);
			marker.openInfoWindowHtml(this.name);

	      }
	    }
	
});


var PrivateWidgets = Class.create({
	itemChoosers:new Object(),
	itemSliderManager:null,
	mapManagers: new Object(),
	
	getItemSliderManager:function(){ return this.itemSliderManager; },
	
	addItemChooser: function(id,actionFile,parameters,trashActionFile){ this.itemChoosers[id] = new ItemChooser(id,actionFile,parameters,trashActionFile); },
	getItemChooser: function(id){ return this.itemChoosers[id]; },
	
	addMapManager: function(id,mapType,centerLatitude,centerLongitude,latitude,longitude,zoom,name) {
		this.mapManagers[id] = new MapManager(mapType,centerLatitude,centerLongitude,latitude,longitude,zoom,name);
	},
	
	getMapManager: function(id){
		return this.mapManagers[id];
	},
	
	loadMaps: function() {
		for (var key in this.mapManagers) {
			this.mapManagers[key].loadMap();
		}
	},
	
	loadEditMaps: function() {
		for (var key in this.mapManagers) {
			this.mapManagers[key].loadEditMap();
		}
	}
	
});

var fileUploadersManager = new FileUploadersManager();
var privateWidgets = new PrivateWidgets();
var itemSliderManager = new ItemSliderManager();
var imageEffectsManager = new ImageEffectsManager();
privateWidgets.itemSliderManager = itemSliderManager;

document.observe('ws:file_upload_success',function (event) { if (event.memo.error) { fileUploadersManager.uploadError(event); } else if (event.memo.warning) { fileUploadersManager.uploadWarning(event); } else { fileUploadersManager.uploadSuccess(event); } });
document.observe('ws:file_upload_error',function (event) { fileUploadersManager.uploadError(event); });
