
/* Upload photo handler */

var subscr={
	_Init:function(){		this.securePsw._Init();
		this.cp._Init();
        
		this.upLoad._Init();
	}	
	
	,cp:{
		_Init:function(){
			subscr.cp.datas={};
            
			// comportement du select
			$("pays").addEvent("change",function(e){
				var e=new Event(e);
				var value=$("pays").value;
				//si valeur par défaut
				if(value=="0"){
					//$("cacheCp").removeClass("displayNone");
					$("drouleCp").disabled="disabled";
					$("drouleCp").value=lang.front["drouleCp"];
					$("updCP").innerHTML="";
				}else{ // sinon
					//$("cacheCp").addClass("displayNone");
					$("drouleCp").disabled="";
					$("drouleCp").value=lang.front["drouleCp"];
					$("updCP").innerHTML="";
				}
			});
            
			// comportement du champ texte
			$("drouleCp").addEvent("keypress", function(e){
				var monForm=ydyleForm._Init("#inscriptForm");
				var e=new Event(e);
				var el=e.target;
				var cpToSearch=el.value+String.fromCharCode(e.code);

				$("drouleCp").setAttribute("maxlength", (cpToSearch!=lang.front["drouleCp"]) ? "8" : ""+lang.front["drouleCp"].length+"");
				if(subscr.cp.myTimer){subscr.cp.myTimer = $clear(subscr.cp.myTimer);}
				if(cpToSearch.length>=3){
					subscr.cp.myTimer = subscr.cp._RequestCp.delay(500, el); //wait 2 seconds and execute my function.
				}else{	
					$("updCP").innerHTML="";
				}
				e.stopPropagation();
			});

			$("drouleCp").addEvent("focus", function(e){
				var e=new Event(e);
				var el=e.target;

				($("drouleCp").value==lang.front["drouleCp"]) ? $("drouleCp").value="" : $("drouleCp").select() ;
				$("drouleCp").maxlength="8";
				e.stopPropagation();
			});

			$("drouleCp").addEvent("blur", function(e){
				var e=new Event(e);
				var el=e.target;
				if($("drouleCp").value==lang.front["drouleCp"] || $("drouleCp").value.clean()==""){
					$("drouleCp").maxlength=lang.front["drouleCp"].length;
					$("drouleCp").value=lang.front["drouleCp"];
				}
				e.stopPropagation();
			});
            
           
			
			//comportements si les éléments sont préremplis
			var monForm=ydyleForm._Init("#inscriptForm");
			// si le select n'a pas la valeur par défaut
			if(monForm.formValues.pays!="0"){
				//$("cacheCp").addClass("displayNone");
				$("drouleCp").disabled="";
				// si le champ cp n'a pas la valeur par défaut
				if(monForm.formValues.drouleCp != lang.front["drouleCp"]){
					//subscr.cp._RequestCp();
				}
			}
		}
		,_RequestCp:function(){
			var monForm=ydyleForm._Init("#inscriptForm");
			if($type(subscr.cp.datas[monForm.formValues.pays]) == false){
				subscr.cp.datas[monForm.formValues.pays]={};
			}
			if($type(subscr.cp.datas[monForm.formValues.pays][monForm.formValues.drouleCp])==false){
				var maData={zipcode:monForm.formValues.drouleCp, iso_code:monForm.formValues.pays, lang:lang.currentLang};
				var getLog = new Ajax("http://www.ydyle.com/modules/home/inscription/_getCity_zipcode_country.php", {
					method: 'post'
					, data: maData
					,onSuccess:function(responseText){
						subscr.cp.datas[monForm.formValues.pays][monForm.formValues.drouleCp]=responseText;
						subscr.cp._CompleteRequestCp(subscr.cp.datas[monForm.formValues.pays][monForm.formValues.drouleCp]);
					}
				}).request();
			}else{
				subscr.cp._CompleteRequestCp(subscr.cp.datas[monForm.formValues.pays][monForm.formValues.drouleCp]);
			}
		}
		,_CompleteRequestCp:function(responseText){
			$E("#updCP").innerHTML=responseText;
		}
	}
	,securePsw:{
		_Init:function(){
			var cible=$E("#password");
			cible.addEvents({
				"keyup":function(e){
					e = new Event(e).stop();
					var valuePass=e.target.value;
					var moduleSecure=$E("#mainContentJauge");
					var setJauge=$E("#setJauge");
					var textJauge=$E("#textJauge");
					var forceSecure="faible";
					//lang.front.textJauge[forceSecure]
					var isModuleSecure=false;
					var pcentSecure=0;

					if(valuePass!="" && !isModuleSecure){
						moduleSecure.className="displayBlock";
						isModuleSecure=true;
						pcentSecure=subscr.securePsw._VerifSecurePsw(valuePass);//lancement de la fonction de vérification de caractères

						if(pcentSecure<=35) forceSecure="faible";
						if(pcentSecure>35 && pcentSecure<=65) forceSecure="moyen";
						if(pcentSecure>65) forceSecure="fort";

						textJauge.setText(lang.front.textJauge[forceSecure]);
						setJauge.className=forceSecure;
						setJauge.style.width=pcentSecure+"%";

					}else{
						moduleSecure.className="displayNone";
						isModuleSecure=false;

					}//de l'affichage ou non du module de niveau de sécurité du mot de passe
				}
			});// value select on focus // submit form on key press enter
		}
		,_VerifSecurePsw:function(valuePass){
			var pcentSecure=0;
			var valuePass=valuePass;
			var valuePassLength=valuePass.length;
			var valuePass=valuePass.escapeRegExp();

			// test de la longueur de caractère
			if(valuePassLength>=6){
				if(valuePassLength>=6) pcentSecure+=10;
				if(valuePassLength>=8) pcentSecure+=10;
				if(valuePassLength>=10) pcentSecure+=10;

				// test des expressions régulières simples

				if(/^([a-z]+|[A-Z]+)$/.test(valuePass)) return(pcentSecure); // only standard caractères without alternate of fat and low case
				if(/^[a-zA-Z]+$/.test(valuePass)) return(pcentSecure+10); // only standard caractères with alternate of fat and low case
				if(/^[\d]+$/.test(valuePass)) return(pcentSecure+60); // only numbers
				if(/^[^a-zA-Z0-9]+$/.test(valuePass)) return(pcentSecure+70); // only specials chars

				// test des imbriquations d'expression régulières

				if(/[a-z]+/.test(valuePass)){// at least one small cap
					if(/[A-Z]+/.test(valuePass)){// at least one fat cap
						if(/[0-9]+/.test(valuePass)){// at least one number
							if(/[^a-zA-Z0-9]+/.test(valuePass)){// at least one special chars
								return(pcentSecure+70);
							}else{
								return(pcentSecure+50);
							}
						}else if(/[^a-zA-Z0-9]+/.test(valuePass)){// at least one special chars
							return(pcentSecure+60);
						}
					}
				}else if(/[A-Z]+/.test(valuePass)){
					if(/[0-9]+/.test(valuePass)){// at least one number
						if(/[^a-zA-Z0-9]+/.test(valuePass)){// at least one special chars
							return(pcentSecure+50);
						}else{
							return(pcentSecure+30);
						}
					}else if(/[^a-zA-Z0-9]+/.test(valuePass)){// at least one special chars
						return(pcentSecure+40);
					}
				}else if(/[0-9]+/.test(valuePass)){
					if(/[^a-zA-Z0-9]+/.test(valuePass)){// at least one special chars
						return(pcentSecure+50);
					}else{
						return(pcentSecure+30);
					}
				}
			}
			return(pcentSecure);
		}
	}
	,upLoad:{
		_Init:function(){
			// Initialisation de l'upload
			subscr.upLoad.upPict._Init();
			// comportement de rotation
			$("rotatePhoto").addEvent("click",function(e){
				var e=new Event(e).stop();
				subscr.upLoad.upPict._RotatePict();
			});
			
			// inclusion du swf
			/*
			var so = new SWFObject("http://www.ydyle.com/medias/swf/test_swf_plugin.swf", "swfTextPlugin", "214", "137", "9", "#FFFFFF");
			so.useExpressInstall("http://www.ydyle.com/medias/swf/expressinstall.swf");
			so.setAttribute("xiRedirectUrl", "http://www.ydyle.com/modules/home/inscription/etape6.php");
			so.addParam("wmode", "transparent");
			so.write("testFlash");
			*/
			// variables par défaut
			/*
			subscr.upLoad.upPict={}
			subscr.upLoad.upPict.drag="";
			subscr.upLoad.upPict.objectRequest={};
			subscr.upload.upPict={}
			subscr.upload.drag="";
			subscr.upload.objectRequest={};
			*/
		}
		,upPict:{
			drag:""
			,objectRequest:{}
			,_UploadFileComplete:function(file){
				var maData={
			    	file:"http://files.ydyle.com/modules/home/inscription/_upload_avatar.php?ses_inscr=ba30l40bjdj8eg9952n8oa22d7&id_avatar="+file.id+"&lang="+lang.currentLang
			        , id_avatar:file.id
			        , lang:lang.currentLang
			    };
				var getLog = new Ajax("http://www.ydyle.com/read_file.php",{
					data: maData
					,method: 'post'
					,onSuccess:function(responseText){
						subscr.upLoad.upPict.objectRequest=Json.evaluate(responseText);
						if(subscr.upLoad.upPict.objectRequest.response=="ok"){
							$E(".photoCanevas").style.cursor="move";
							
							$E(".photoCanevas img").style.left="3px";
							$E(".photoCanevas img").style.top="3px";
							
							$("posAvatar").value='{"posSubs":{"top":"'+$E(".photoCanevas img").style.top+'","left": "'+$E(".photoCanevas img").style.left+'","position":"absolute"}, "posStand":{"top":"9px","left":"12px","position":"absolute"}}';
							
							$E(".photoCanevas img").className="displayBlock";
							$E(".photoCanevas img").setAttribute("src", subscr.upLoad.upPict.objectRequest.url);
							$E(".photoCanevas img").width=subscr.upLoad.upPict.objectRequest.width;
							$E(".photoCanevas img").height=subscr.upLoad.upPict.objectRequest.height;
							$("urlAvatar").value=subscr.upLoad.upPict.objectRequest.url;
							subscr.upLoad.upPict._InitDrag();
							$("rotatePhoto").removeClass("visibilityHidden");
						}else if(subscr.upLoad.upPict.objectRequest.response=="ko"){
							$("errorUpload").append(htmlConstruct._SetNode("p", {}, subscr.upLoad.upPict.objectRequest.msg));
							(function(){subscr.upLoad.upPict.objectRequest.url;}).delay(1000);
						}
					}
				}).request();
			}
			,_Init:function(){
				subscr.upLoad.upPict._InitDrag();
				subscr.upLoad.upPict.tabError=new Array();
				subscr.upLoad.swfu = new SWFUpload({
					// Backend Settings
					upload_url: "http://files.ydyle.com/modules/home/inscription/_upload_avatar.php?ses_inscr=ba30l40bjdj8eg9952n8oa22d7",	// Relative to the SWF file
					movieName:"swfuName",
					// File Upload Settings
					file_size_limit : "16384",//"16384",	// 16MB
					file_types : "*.jpg;*.gif;*.png;*.jpeg",
					file_types_description : "JPG, GIF or PNG Images",
					file_upload_limit : "0",
					// Event Handler Settings - these functions as defined in Handlers.js
					// The handlers are not part of SWFUpload but are part of my website and control how
					// my website reacts to the SWFUpload events.

					file_dialog_complete_handler : fileDialogComplete,
					file_queue_error_handler : fileQueueError,
					upload_error_handler : uploadError,
					upload_progress_handler : uploadProgress,
					upload_success_handler : uploadSuccess,
					upload_complete_handler : uploadComplete,

					prevent_swf_caching : true,

					// Flash Settings
					flash_url: "http://files.ydyle.com/medias/swf/swfupload.swf",	// Relative to this file


					// Button Settings
					//button_image_url : "../applicationdemo/images/SmallSpyGlassWithTransperancy_17x18.png",	// Relative to the SWF file
					button_placeholder_id : "containtBrowsPictSpan",
					button_width: 264,
					button_height: 20,
					button_text : '<span class="containtBrowsPict"><span>Parcourir</span></span>',
					button_text_style : '.containtBrowsPict { display: block; text-align: center;font-family: \"Trebuchet MS\", sansSerif; font-size: 16px; color: #FD3489; font-weight:bold}',// span span{border: solid 1px #F00; padding: 10px; background-color: #F0F}
					button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
					button_cursor: SWFUpload.CURSOR.HAND,

					customSettings:{
						upload_target:'ulUpload'
					},

					// Debug Settings
					debug: false
				});
				/*
				$E("#btParcourirPhoto a").addEvent("click",function(e){
					var e = new Event(e);
					e.stop();
					etpSix.swfu.selectFile();
				});
				*/
			}
			,_UploadFileStart:function(){
				if(subscr.upLoad.upPict.drag!=""){
					subscr.upLoad.upPict.drag.detach();
					subscr.upLoad.upPict.objectRequest={};
				}
				$E(".photoCanevas img").className="displayNone";
			}
			,_InitDrag:function(){
				if($E(".photoCanevas img").getSize().size.x>83 || $E(".photoCanevas img").getSize().size.y>83 || $E(".photoCanevas img").width.toInt()>83 || $E(".photoCanevas img").height.toInt()>83){
					$E(".photoCanevas").style.cursor="move";
					if($type($E(".photoCanevas img").width)!=false){
						var elemWidth= $E(".photoCanevas img").width;
					}else{
						var elemWidth= $E(".photoCanevas img").width=$E(".photoCanevas img").getSize().size.x;
					}
					if($type($E(".photoCanevas img").height)!=false){
						var elemHeight= $E(".photoCanevas img").height;
					}else{
						var elemHeight= $E(".photoCanevas img").height=$E(".photoCanevas img").getSize().size.y;
					}

					$E(".photoCanevas img").className="displayBlock";
					if($type(subscr.upLoad.upPict.drag)!=false){
						delete(subscr.upLoad.upPict.drag);
						subscr.upLoad.upPict.drag={};
						$E(".photoCanevas").removeEvents();
						$E(".photoCanevas img").removeEvents();
					}

					subscr.upLoad.upPict.drag=new Drag.Move($E(".photoCanevas img"), {
						handle: $E(".photoCanevas")
						,limit:{x:[(($E(".photoCanevas img").width.toInt()==83) ? 3 : (ydyle._GetParentByClass($E(".photoCanevas img"), "photoCanevas").getSize().size.x - $E(".photoCanevas img").width.toInt())) ,3],y:[(($E(".photoCanevas img").height.toInt()==83) ? 3 : (ydyle._GetParentByClass($E(".photoCanevas img"), "photoCanevas").getSize().size.y - $E(".photoCanevas img").height.toInt()) ),3]}
						,onComplete:function(){
							$("posAvatar").value='{"posSubs":{"top": "'+this.element.style.top+'", "left": "'+this.element.style.left+'", "position":"absolute"}, "posStand":{"top":"'+(this.element.style.top.toInt()+6)+'px", "left": "'+(this.element.style.left.toInt()+9)+'px", "position":"absolute"}}';
						}
					});
				}
			}
			,_RotatePict:function(){
				// variables à utiliser.
				var height = $E(".photoCanevas img").height.toInt();
				var width = $E(".photoCanevas img").width.toInt();
				var src = ($E(".photoCanevas img").src.indexOf("?") != -1) ? $E(".photoCanevas img").src.replace($E(".photoCanevas img").src.substring($E(".photoCanevas img").src.indexOf("?")),"") : $E(".photoCanevas img").src ;
				subscr.upLoad.upPict.requestRotatePict = new Ajax("http://www.ydyle.com/read_file.php",{
					method: 'get'
					,data: {file:"http://files.ydyle.com/modules/home/inscription/_rotate_img.php?lang="+lang.currentLang+"&url_img="+src}
					,onRequest:function(){
						$("rotatePhoto").addClass("visibilityHidden");
						$("contentRotateLink").addClass("load");
					}
					,onFailed:function(){
						$("rotatePhoto").removeClass("visibilityHidden");
						$("contentRotateLink").removeClass("load");
					}
					,onSuccess:function(responseText){
						var statusResponse=Json.evaluate(responseText);
						if (statusResponse.response == "ok") {
							var D = new Date();
							// traitement a la fin de la requète

							// inversion du height et du width
							$E(".photoCanevas img").height = statusResponse.new_height;
							$E(".photoCanevas img").width = statusResponse.new_width;

							// rafraichissement de la source de l'image
							$E(".photoCanevas img").src = src+"?"+D.getTime();

							// initialisation du drag et des valeurs top et left
							$E(".photoCanevas img").style.left=3+"px";
							$E(".photoCanevas img").style.top=3+"px";

							subscr.upLoad.upPict._InitDrag();
						}else{
							ydyle.alertMsg._Open(htmlConstruct._SetNode("p", {}, statusResponse.msg), "wrong");
						}	
						$("rotatePhoto").removeClass("visibilityHidden");
						$("contentRotateLink").removeClass("load");
					}
				}).request();
			}
		}
	}
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if(subscr.upLoad.upPict.tabError.tabError>0){
			afficheErrorMsg();
		}else{
			this.startUpload();
			$("containtBrowsPict").style.top="-300px";
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		var progress = new FileProgress(file,  this.customSettings.upload_target);
		if(subscr.upLoad.upPict.tabError.length>0){
			afficheErrorMsg();
		}else{
			progress.setComplete();
			progress.setStatus("image received.");
			subscr.upLoad.upPict._UploadFileComplete(file);
			progress.toggleCancel(false);
			$("containtBrowsPict").style.top="160px";
			progress.setStatus("");
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	var progress;
	try {
		if(errorCode===SWFUpload.UPLOAD_ERROR.FILE_CANCELLED){
			try {
				subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.fileCancelled));
				progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setCancelled();
				progress.setStatus("Cancelled");
				progress.toggleCancel(false);
			}
			catch (ex1) {
				this.debug(ex1);
			}
		}else if(errorCode===SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED){	
			try {
				subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.uploadStopped));
				progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setCancelled();
				progress.setStatus("Stopped");
				progress.toggleCancel(true);
			}
			catch (ex2) {
				this.debug(ex2);
			}
		}else if(errorCode===SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED){
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.uploadLimitExceeded));
		}else{
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.defaultError));
		}
	} catch (ex3) {
		this.debug(ex3);
	}
}

function fileQueueError(file, errorCode, message) {
	try{
		if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.queueLimitExceeded));
		}else if(errorCode === SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE){
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.zeroByteFile));
		}else if(errorCode === SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT){
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.fileExceedsSizeLimit));
		}else if(errorCode === SWFUpload.QUEUE_ERROR.INVALID_FILETYPE){
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.invalidFiletype));
		}else{
			subscr.upLoad.upPict.tabError.push(htmlConstruct._SetNode("li", {}, file.name +" : "+lang.front.upload.defaultError));
		}
	}catch(ex){
		this.debug(ex);
	}
}

function afficheErrorMsg(){
	var divContainer=htmlConstruct._SetNode("div", {});
	var bodyMsg=htmlConstruct._SetNode("ul", {});
	for(var i=0; i<subscr.upLoad.upPict.tabError.length; i++){
		htmlConstruct._GoodAppendChild(bodyMsg, subscr.upLoad.upPict.tabError[i]);
	}
	htmlConstruct._GoodAppendChild(divContainer, bodyMsg);
	ydyle.alertMsg._Open(divContainer, "wrong");
	subscr.upLoad.upPict.tabError=new Array();
}

function uploadProgress(file, bytesLoaded) {
	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		var progress = new FileProgress(file);
		if (percent === 100) {
			progress.setStatus("Upload complete...");
			progress.toggleCancel(false, this);
		}else if(percent === 0){
			percent=100;
			progress.setStatus("Upload complete...");
		}else {
			progress.setStatus(" Uploading "+percent+"%");
			progress.toggleCancel(true, this);
		}
		progress.setProgress(percent);
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.upload_target);

	//	progress.setStatus("Thumbnail Created.");
		progress.toggleCancel(false);

	} catch (ex) {
		this.debug(ex);
	}
}


function FileProgress(file, targetID) {}

FileProgress.prototype.setProgress = function (percentage) {
	$("pcentPhoto").innerHTML = "Uploading "+percentage + "%";
};
FileProgress.prototype.setComplete = function () {};
FileProgress.prototype.setError = function () {};
FileProgress.prototype.setCancelled = function () {};
FileProgress.prototype.setStatus = function (status) {
	$("pcentPhoto").innerHTML = status;
};

FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
	
	if (swfuploadInstance){
		var fileID = this.fileProgressID;
	}
};