// JavaScript Document
var uploader ;
var fileID;
var DED = window.DED || {};
	
	/* A quick and dirty trim function available to all string objects */
	String.prototype.trim = function() {
		var l = /^(\s*)/g;
		var r = /(\s*)$/g;
		var str = this;
		str = str.replace(l,'');
		str = str.replace(r,'');
		return str;
	};
	/* 
		* The effects subdomain of DED 
		* Feel free to extend it if you want.
		* Otherwise, all you're gonna get is 'shake' :)
	*/
	DED.effects = function() {
		var $D = YAHOO.util.Dom;
		var $M = YAHOO.util.Motion;
		return {
			/*
				@param {String/HTMLElement} | oEl : Accepts a string to use as an ID for getting a DOM reference, or an actual DOM reference
				@param {Int} | iOffset : The unit (in 'px') that the element will be shaken 'by'
				@param {Int} | iNum : The number of times the motion will iterate
				@param {Int} | iSpeed : The speed at which the motion will animate
			*/
			shake : function(oEl, iOffset, iNum, iSpeed) {
				var xy = $D.getXY(oEl);
				var left = xy[0]-iOffset;
				var right = xy[0]+iOffset;
				(function(type, args, count) {
					if ( count >= iNum ) {
						var a = { 
							points : {
								to : xy
							}
						};
						var anim = new $M(oEl, a, iSpeed);
						anim.animate();
						return;
					}
					else if ( count % 2 ) {
						var c = count+1;
						var a = { 
							points : {
								to : [right, xy[1]]
							}
						};
						var anim = new $M(oEl, a, iSpeed);
						anim.onComplete.subscribe(arguments.callee, c);
						anim.animate();
					}
					else {
						var c = count+1;
						var a = { 
							points : {
								to : [left, xy[1]]
							}
						};
						var anim = new $M(oEl, a, iSpeed);
						anim.onComplete.subscribe(arguments.callee, c);
						anim.animate();
					}
				})(null, null, 1);
			}
		};
	}();
	DED.core = function() {
		var $D = YAHOO.util.Dom;
		var $E = YAHOO.util.Event;
		var $A = YAHOO.util.Anim;
		var $M = YAHOO.util.Motion;
		var $DD = YAHOO.util.DD;
		var $C = YAHOO.util.Connect;
		var $ = $D.get;
		var required, emails, form, logger, sFailureMsg, sUrl, iFormHeight, oSpinner;
		/* 
			private methods. No need to open these up
		*/
       sFailureMsg="";
       sSuccessMsg="";
		var sendEmailRequest = function() {
            
			$C.setForm(form);
			var attrForm = {
				height : {
					to : iFormHeight
				}
			};
			var attrMsg = {
				height : {
					to : 0
				}
			};
			var successful = false;
			var animForm = new $A($(form), attrForm, 0.5, YAHOO.util.Easing.easeOut);
			var animMsg = new $A('ded-status', attrMsg, 0.3, YAHOO.util.Easing.easeOut);
			var success = function(o) {
				var fn = function() {
                   // alert(o.responseText);
					var mail_status = eval(o.responseText);
                   
					if ( mail_status != 1 ) {
                        sSuccessMsg="";
						failure(mail_status);
						return;
					}
                    else
                    {
                        sSuccessMsg='Grazie per averci contattato.';
                        successful = true;
                    }
					
					animForm.onComplete.subscribe(function() {
                      
							var animMsg = new $A('ded-status', { height : { to : 20 } }, 0.3, YAHOO.util.Easing.easeOut);
							$('ded-status').innerHTML = '<p class="ded-success">'+sSuccessMsg+'</p>';
							animMsg.animate();
                          
						}
					);
					animForm.animate();
					animMsg.animate();
				};
				setTimeout(function(){ fn(); }, 2000);
			};
			var failure = function(esito) {
				if ( esito==1 ) {
                    sFailureMsg="Email inviata";
					return ;
				}
                else if(esito==2)
                {
                       sFailureMsg="Email non esatta";
                 }
                 else if(esito==3)
                {
                       sFailureMsg="Privacy non sottoscritta.";
                 }
                 else if(esito==4)
                 {
                       sFailureMsg="Errore generico. ";
                 }
                  else if(esito==5)
                 {
                       sFailureMsg="Errore nell allegato. ";
                 }
                 else
                 {
                     esito=false;
                 }

				animForm.onComplete.subscribe(function() {

                  if(sSuccessMsg=='')
                      {
                            var animMsg = new $A('ded-status', { height : { to : 20 } }, 0.3, YAHOO.util.Easing.easeOut);
                            $('ded-status').innerHTML = '<p class="ded-error">'+sFailureMsg+'</p>';
                            animMsg.animate();
                      }
                       
					}
				);
				animForm.animate();
				animMsg.animate();
				return;
			};
			var callback = {
				success : success,
				failure : failure
			};
			var req = $C.asyncRequest('POST', sUrl, callback);
			setTimeout(function(){ YAHOO.util.Connect.abort(req); failure(); },5000);
		};
		var slideUp = function() {
			var attributes = {
				height : {
					to : 0
				},
				paddingTop : {
					to : 0
				},
				paddingBottom : {
					to : 0
				}
			};
			var anim = new $A($(form), attributes, 0.5, YAHOO.util.Easing.easeOut);
			anim.onStart.subscribe(sendEmailRequest);
			anim.onStart.subscribe(function() {
					$(form).style.overflow = 'hidden'; 
				}
			);
			anim.onComplete.subscribe(function() {
					oSpinner = $('ded-status');
					oSpinner.style.overflow = 'hidden';
					oSpinner.style.height = '0';
					oSpinner.innerHTML = '<span>In elaborazione...</span>';
					var anim = new $A(oSpinner, { height : { to : 20 } }, 0.5, YAHOO.util.Easing.easeOut);
					anim.animate();
				}
			);
			anim.animate();
		};
		return {
			init : function(opt) {
				form = opt.form;
				sFailureMsg = opt.sFailureMsg;
				sUrl = opt.sUrl;
				sSuccessMsg = opt.sSuccessMsg;
				iFormHeight = parseInt($(form).offsetHeight);
				required = $D.getElementsByClassName('required');
				$E.on(form, 'submit', DED.core.validate, required);
				$E.on(required, 'blur', DED.core.validate);
			},
			validate : function(e, oEl) {
				$E.stopEvent(e);
				var valid = true;
				var required = [];
				if ( e.type !== 'submit' ) {
					var oEl = this.value.trim();
					if ( oEl === '' ) {
						// shake : function(oEl, iOffset, iNum, iSpeed)
						DED.effects.shake(this, 12, 6, 0.1);
					}
                   
					return;
				}
				else {
					for ( var i=0, len=oEl.length; i<len; i++ ) {
						oEl[i].value = oEl[i].value.trim();
						if ( oEl[i].value === '' ) {
							// shake : function(oEl, iOffset, iNum, iSpeed)
							DED.effects.shake(oEl[i], 12, 6, 0.1);
							valid = false;
                            required.push(oEl[i]);
						}
					}
				}
				if ( valid ) {
					slideUp();
				}
				else {
					// focus our first errored element
					required[0].focus();
				}
			}
		};
	}();
	DED.contactDetails = {
		form : 'contact',
		sFailureMsg : '',
		sSuccessMsg : 'Grazie per averci contattato.',
		sUrl : 'invio_email.php?ajax=1' // Make sure ajax=1 !!!!
	};
	DED.workDetails = {
		form : 'work_us',
		sFailureMsg : '',
		sSuccessMsg : 'Grazie per averci contattato.',
		sUrl : 'invio_curriculum.php?ajax=1' // Make sure ajax=1 !!!!
	};
