/**
 * @author Ferran_
 */

var sid;
var fotosubida = false;

window.addEvent('domready', function(){
	var req = new Request({
        method: 'post',
        url: '/ajax/upload.php',
        data: {
            accion: 'sid'
        },
        onComplete: function(e){
			sid = e;
			window.fireEvent('domready-upload');
		}
    }).send();
});

window.addEvent('domready-upload', function() { // wait for the content
 
	// our uploader instance 
	
	if ($('form-demo')) {
		var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
			// we console.log infos, remove that in production!!
			verbose: false,
			
			multiple: false,
			
			instantStart: true,
			
			// url is read from the form, so you just have to change one place
			url: $('form-demo').action+'?sid='+sid,
			
			// path to the SWF file
			path: '/includes/Swiff.Uploader.swf',
			
			// remove that line to select all files, or edit it, add more items
			typeFilter: {
				'Images (*.jpg, *.jpeg)': '*.jpg; *.jpeg'
			},
			
			// this is our browse button, *target* is overlayed with the Flash movie
			target: 'demo-browse',
			
			fileSizeMax: 3 * 1024 * 1024,
			
			onSelectSuccess: function(files) {
			
				//$('demo-browse').toggleClass('nodisplay');
				$('demo-browse').set('styles', {
					    'display': 'none'
					}
				);
				$('precarga').toggleClass('nodisplay');
				if($('publica_tu_foto')){
					if ($('publica_tu_foto').hasClass('nodisplay')) {
					}
					else {
						$('publica_tu_foto').addClass('nodisplay');
					}
				}
				
			},
			
			
			// graceful degradation, onLoad is only called if all went well with Flash
			onLoad: function(){
				//$('demo-status').removeClass('hide'); // we show the actual UI
				//$('demo-fallback').destroy(); // ... and hide the plain form
				
				// We relay the interactions with the overlayed flash to the link
				this.target.addEvents({
					click: function(){
						return false;
					},
					mouseenter: function(){
						this.addClass('hover');
					},
					mouseleave: function(){
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function(){
						this.focus();
					}
				});
				
				// Interactions for the 2 other buttons
				/*
				$('demo-clear').addEvent('click', function(){
					up.remove(); // remove all files
					return false;
				});
				
				$('demo-upload').addEvent('click', function(){
					up.start(); // start upload
					return false;
				});
				*/
			},
			
			// Edit the following lines, it is your custom event handling
			
			/**
		 * Is called when files were not added, "files" is an array of invalid File classes.
		 *
		 * This example creates a list of error elements directly in the file list, which
		 * hide on click.
		 */
			onSelectFail: function(files){
				files.each(function(file){
					alert(file.validationErrorMessage+' : '+file.validationError);
					new Element('li', {
						'class': 'validation-error',
						html: file.validationErrorMessage || file.validationError,
						title: MooTools.lang.get('FancyUpload', 'removeTitle'),
						events: {
							click: function(){
								this.destroy();
							}
						}
					}).inject(this.list, 'top');
				}, this);
			},
			
			/**
		 * This one was directly in FancyUpload2 before, the event makes it
		 * easier for you, to add your own response handling (you probably want
		 * to send something else than JSON or different items).
		 */
			onFileSuccess: function(file, response){
				var json = new Hash(JSON.decode(response, true) ||
				{});
				
				alert('Imagen subida correctamente. Ahora recortala y pulsa el botón de publicar foto.');
				
				if (json.get('status') == '1') {
					fotosubida=true;
					file.element.addClass('file-success');
					file.info.set('html', '<strong>Image was uploaded:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px, <em>' + json.get('mime') + '</em>)');
					
					//alert(json.rutaimagen);
					
					$('foto').set('html','');
					$('foto').set('html',json.rutaimagen);
					
					if($$('.cropmask')){
						$$('.cropmask').each(function(el,i){
							if(el.hasClass('nodisplay')){
							}else{
								el.addClass('nodisplay')
							}
						});
					}
					
					if($('publica_tu_foto')){
						$('publica_tu_foto').toggleClass('nodisplay');
					}
					
					myCropper = new ByCropper('bycropper', null, {
						borderPath: '/js/crop',
						maskColor: "#000000",
						minWidth: 150,
						minHeight: 150,
						maskOpacity: 0.8
					});
					
					$('demo-browse').set('styles', {
						    'display': 'block'
						}
					);
					$('precarga').toggleClass('nodisplay');
					//location.href = '/registro2.php';
				}
				else {
					logError(json.get('error')+': '+response);
					file.element.addClass('file-failed');
					file.info.set('html', '<strong>An error occured:</strong> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response));
					//alert('Ha ocurrido un error: '+ (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response));
					alert('Ha ocurrido un error: '+ (json.get('error')));
					$('demo-browse').set('styles', {
						    'display': 'block'
						}
					);
					$('precarga').toggleClass('nodisplay');
				}
			},
			
			onComplete: function(){
				//location.href = '/registro2.php';
			},
			/**
		 * onFail is called when the Flash movie got bashed by some browser plugin
		 * like Adblock or Flashblock.
		 */
			onFail: function(error){
				switch (error) {
					case 'hidden': // works after enabling the movie and clicking refresh
						//alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
						break;
					case 'blocked': // This no *full* fail, it works after the user clicks the button
						//alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
						break;
					case 'empty': // Oh oh, wrong path
						//alert('A required file was not found, please be patient and we fix this.');
						break;
					case 'flash': // no flash 9+ :(
						//alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
				}
			}
			
		});
	}
	
	if($('bycropper_form'))
	{
		if ($('aceptar_texto_foto')) {
		
			$('aceptar_texto_foto').addEvent('click', function(e){
				new Event(e).stop();
				textoligue = $('frase_ligue').get('value');
				if ((textoligue == 'escribe aquí tu frase' || textoligue == '') && !fotosubida) {
					//alert('Tienes que escribir tu frase para ligar y subir una foto.');
					//enviar a partida//
					location.href = '/partida.php';
				}
				else if(textoligue == 'escribe aquí tu frase' || textoligue == ''){
					alert('Tienes que escribir tu frase para ligar.');
				}
				else if(!fotosubida){
					//alert('Tienes que subir una foto.');
					//guardar text i enviar a partida//
					cambioTexto(textoligue);
				}
				else {
					$('textomsj').value = textoligue;
					$('bycropper_form').submit();
				}
			});
			
		}
		
		if ($('publicar_foto')) {
			$('publicar_foto').addEvent('click', function(e){
				new Event(e).stop();
				$('bycropper_form').submit();
			});
		}	
	}
	
	
});

function cambioTexto(texto){
	var req = new Request({
        method: 'post',
        url: '/ajax/micuenta.php',
        data: {
            accion: 'cambiotexto',
			texto: texto
        },
        onComplete: function(e){
			
		},
		onSuccess: function(){
			location.href = '/partida.php';	
		}
    }).send();
}

function logError(errores){
	var req = new Request({
        method: 'post',
        url: '/ajax/logerror.php',
        data: {
            accion: 'logerror',
			error: errores
        },
        onComplete: function(e){
			
		}
    }).send();
}