var firstTime = true;
var capa,capaLoading;
var targetPage;
var targetPageGafas;

var oImg = {
	zoom : 0,
	zoomGafa : -0.7,
	hash : false,
	originalw:0,
	originalh:0,
	originalwGafa:0,
	originalhGafa:0,
	gafaObj : null,
	offsetX:0,
	offsetY:0,
	offsetXGafa:0,
	offsetYGafa:0,
	rotate:0,
	rotateOffset:2,
	rotatemax:30,
	id_gafaPuesta : null,
	editing : true,
	gafaPuesta : {
		litZ : 'zoomGafa',
		litw : 'originalwGafa',
		lith : 'originalhGafa',
		litOx : 'offsetXGafa',
		litOy : 'offsetYGafa'
	},
	fSubida : {
		litZ : 'zoom',
		litw : 'originalw',
		lith : 'originalh',
		litOx : 'offsetX',
		litOy: 'offsetY'
	},
	gObj : function(lit) {
		return oImg[oImg.selectedPic][lit];
	},
	sObj : function(lit) {
		return oImg[oImg.gObj(lit)];

	},
	selPic : function(s) {
		oImg.selectedPic = s;
		if (s == "fSubida") {
			$("#fSubida").css("opacity","1");
			$("#ffaceSel").css("opacity","1");
			$("#fgafaSel").css("opacity","0.5");
			$("#facebox img.fAccs").each(function() {
				$(this).attr("src",$(this).attr("src").replace(/\/gafa_/,"/reg_"));
			});
			$("#facebox .rots").fadeOut("fast");
		} else {
			$("#fSubida").css("opacity","0.5");
			$("#ffaceSel").css("opacity","0.5");
			$("#fgafaSel").css("opacity","1");
			$("#facebox img.fAccs").each(function() {
				$(this).attr("src",$(this).attr("src").replace(/\/reg_/,"/gafa_"));
			});
			$("#facebox .rots").fadeIn("fast");
		}
	},
	selectedPic : "fSubida",
	setZoom : function(z) {
		oImg[oImg.gObj('litZ')] += z;
	},
	redraw : function(arg) {

		var sjObj = ((typeof(arg) == "undefined")? oImg.selectedPic:arg);
		var currSelected = oImg.selectedPic;
		oImg.selectedPic = sjObj;

		jObj = $("#"+sjObj);

		var oL = parseInt(jObj.css("left"));
		var oT = parseInt(jObj.css("top"));

		var oW = parseInt(jObj.width());
		var oH = parseInt(jObj.height());

		var nW = Math.round(((1+oImg.sObj('litZ'))*oImg.sObj('litw')));
		var nH = Math.round(((1+oImg.sObj('litZ'))*oImg.sObj('lith')));

		if (nW < 20) return false;
		if ((oImg.selectedPic == "gafaPuesta") && (nW>$("#facebox").width())) return false;

		var nT = (oT+((oH/2)-(nH/2)));
		var nL = (oL+((oW/2)-(nW/2)));

		jObj.css({'width':nW+'px','top':nT+'px','height':nH+'px','left':nL+'px'});
		oImg.selectedPic = currSelected ;
		jObj.trigger("updatePositions");

	},
	reposTop : function(arg) {
		var sjObj = ((typeof(arg) == "undefined")? oImg.selectedPic:arg);
		var currSelected = oImg.selectedPic;
		oImg.selPic(sjObj);

		jObj = $("#"+sjObj);
		var cWidth = $("#facebox").width();
		var oWidth = oImg.sObj('litw');
		var cHeight= $("#facebox").height();
		var oHeight = oImg.sObj('lith');

		jObj.css({top:((cHeight/2)-(oHeight/2))+'px',left:((cWidth/2)-(oWidth/2))+'px'});
	},
	timeOutGafaOver : null,
	timeOutOffsetOver : 500
};


var helper = {
	setCursorStyle : function(o) {
		o.bind("mousedown",function() {
			$(this).css("cursor","move");
		}).bind("mouseup",function() {
			$(this).css("cursor","move");
		}).css("cursor","move");
	},
	goLoading : function() {
		if (arguments[0] == "transparente") {
			var opct = "0";
		} else {
			var opct ="0.5";
		}
		$("body").css("cursor","ns-wait");
		capaLoading = $("<div id='wcFlash'/>")
			.width($(window).width())
			.height($(document).height())
			.css({opacity:opct,position:"absolute",zIndex:100000,top:'0px',left:'0px',background:'#fff',margin:0,padding:0});
	//	if (opct != "0") {
			var texto = $("<img src='./img/loading_gafa.gif'>").css({opacity:1,marginTop:parseInt(parseInt($(document).height())/2)+'px'});
			texto.appendTo(capaLoading);
	//	}
		capaLoading.appendTo($("body"));

	},
	stopLoading : function() {
		$("body").css("cursor","default");
		capaLoading.fadeOut(function() { $(this).remove();});

	},
	restore : function() {
		$("#sacarFoto p,#sacarFoto h2").fadeIn('fast');


	},
	handleResponse : function(r) {
		$("#fWebcam").hide();
		var ret = false;
		try {
			eval("ret="+r+";");
		} catch (e) {
			helper.restore();
			alert("Error indeterminado subiendo la imagen.");
			return false;
		}

		if ( (ret.error) || (!ret.hash)) {
			if (ret.strerror) alert(ret.strerror);
			else alert("Error indeterminado subiendo la imagen.");
			helper.restore();

		} else {

			oImg.hash = ret.hash.split("=")[1];
			$("#controlsInicial").fadeOut('fast');
			$("#facebox").animate({width:'600px'},1000,function() {
				$("#fSubida").attr("src",ret.hash);
				$("#controlsFinal,#cSelectlens").fadeIn();

			});
		}
	},
	noCam : function() {
		$("#fWebcam").remove();
		$("#idCam").css("cursor","default").unbind("click");
		$("#sacarFoto").css("opacity","0.5");
		helper.handleResponse("{error:true,strerror:'Lo sentimos, no se encuentra su camara.'}");

	},
	haloStart : function(o,autoStop) {
		if (o.data("haling")) return;
		o.css({top:(o.position()['top']+2)+'px',left:(o.position()['left']+2)+'px'}).data("haling",true);
		if (autoStop) {
			window.setTimeout(function() {
				o.css({top:(o.position()['top']-2)+'px',left:(o.position()['left']-2)+'px'});
				o.data("haling",false);
			},250);
		}

	},
	haloStop : function(o) {
		o.css({top:(o.position()['top']-2)+'px',left:(o.position()['left']-2)+'px'});
		o.data("haling",false);
	}

};

$.hasFlash = function() {
    // look for a flag in the query string to bypass flash detection
    if(/hasFlash\=true/.test(location)) return true;
    if(/hasFlash\=false/.test(location)) return false;
    var pv = $.hasFlash.playerVersion().match(/\d+/g);
    var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g);
    for(var i = 0; i < 3; i++) {
        pv[i] = parseInt(pv[i] || 0);
        rv[i] = parseInt(rv[i] || 0);
        // player is less than required
        if(pv[i] < rv[i]) return false;
        // player is greater than required
        if(pv[i] > rv[i]) return true;
    }
    // major version, minor version and revision match exactly
    return true;
};


$.hasFlash.playerVersion = function() {
    // ie
    try {
        try {
            // avoid fp6 minor version lookup issues
            // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch(e) { return '6,0,0'; }
        } catch(e) {}
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
    // other browsers
    } catch(e) {
        try {
            if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch(e) {}
    }
    return '0,0,0';
};




var IntUp,IntDown,IntLeft,IntRight = 0;

$(document).ready(function() {
        if($.hasFlash("10","0","0")) {
            $('#controlsInicialCero').hide();
            $('#controlsInicial').show();
        }
		var targetPage = ($("#probador_medop").length == 1)? "probador_medop.html":"probador.html";
		var targetPageGafas = ($("#probador_medop").length == 1)? "probador_gafas_medop":"probador_gafas";
		$("#donePic").css("opacity","0.2");

		$(".fAccs").bind("mousedown",function() {
			helper.haloStart($(this),false);
		}).bind("mouseup",function() {
			helper.haloStop($(this));
		}).bind("click",function() {

			var aux = 1;
			switch($(this).attr("id")) {
				case "FaceZoomOut": aux = -1;
				case "FaceZoomIn":
					var z = 0.03*aux;
					oImg.setZoom(z);
					oImg.redraw();
				break;
				case "fMoveup":
					$("#"+oImg.selectedPic).trigger("updatePositions",[{top:-3}]);
				break;
				case "fMovedown":
					$("#"+oImg.selectedPic).trigger("updatePositions",[{top:+3}]);
				break;
				case "fMoveleft":
					$("#"+oImg.selectedPic).trigger("updatePositions",[{left:-3}]);
				break;
				case "fMoveright":
					$("#"+oImg.selectedPic).trigger("updatePositions",[{left:+3}]);
				break;
				case "ffaceSel":
					oImg.selPic("fSubida");
				break;
				case "fgafaSel":
					oImg.selPic("gafaPuesta");
				break;
				case "frotateRight":
				case "frotateLeft":
				case "frotateRightmini":
				case "frotateLeftmini":
					var rot = parseInt($(this).attr("alt"))*oImg.rotateOffset;
					if (Math.abs(oImg.rotate+rot)>oImg.rotateMax) return false;
					oImg.rotate += rot;
					var nuevasource = $("#gafaPuesta").attr("src").split("?")[0];
					nuevasource += "?rot="+Math.abs(oImg.rotate);
					if (oImg.rotate<0) nuevasource += "&ca=1";
					helper.goLoading();
					oImg.gafaObj = new Image();
					oImg.gafaObj.src = nuevasource;
					$("#gafaPuesta").attr("src",nuevasource).hide();
					return false;
				break;


			}
		}).bind("mouseover",function() {
			switch($(this).attr("id")) {
				case "ffaceSel":
				case "fgafaSel":
					$(this).css("opacity","1");
				break;
			}

		}).bind("mouseout",function() {
			switch($(this).attr("id")) {
				case "ffaceSel":
					if (oImg.selectedPic == "fSubida") return true;
					$(this).css("opacity","0.5");
				break;
				case "fgafaSel":
					if (oImg.selectedPic == "gafaPuesta") return true;
					$(this).css("opacity","0.5");
				break;
			}

		});


		$("#gafaPuesta").bind("mouseover",function(e) {
			oImg.timeOutGafaOver = window.setTimeout(function() {
				oImg.selPic("gafaPuesta");
			},oImg.timeOutOffsetOver);
		}).bind("mouseout",function() {
			window.clearTimeout(oImg.timeOutGafaOver);
		});

		$("#fSubida").bind("click",function() {
			oImg.selPic("fSubida");
		});



		$(".selectlensbox").bind("click",function(){
			$("img",$(this).parents(".itemsscrollLens")[0]).removeClass("selected");
			$(this).addClass("selected");
			var nuevasource = $("img",$(this)).attr("src").replace(/\/thumb\//,"/normal/");
			oImg.id_gafaPuesta = nuevasource.split("?")[1];
			nuevasource = nuevasource.split("?")[0];
			helper.goLoading();
			nuevasource += "?rot="+Math.abs(oImg.rotate);
			if (oImg.rotate<0) nuevasource += "&ca=1";
			oImg.gafaObj = new Image();
			oImg.gafaObj.src = nuevasource;
			$("#gafaPuesta").attr("src",nuevasource).css("z-index","5000").hide();
			return false;
		});




		$("#facebox").mousewheel(function(e, delta){
			if (oImg.editing == false) return;
			if (delta < 0) {
				oImg.setZoom(-0.02);
				helper.haloStart($("#FaceZoomOut"),true);
				oImg.redraw();
			} else if (delta>0) {
				oImg.setZoom(0.02);
				oImg.redraw();
				helper.haloStart($("#FaceZoomIn"),true);
			} else return false;

			e.stopPropagation();
			e.preventDefault();

			return false;
		});

		$("#fSubida").bind("load",function() {
			oImg.originalw = $(this).width();
			oImg.originalh = $(this).height();
			if (oImg.originalw>oImg.originalh) {
				oImg.originalw = parseInt((oImg.originalw*$("#facebox").height())/oImg.originalh) ;
				oImg.originalh = $("#facebox").height();
			} else {
				oImg.originalh = parseInt((oImg.originalh*$("#facebox").width())/oImg.originalw) ;
				oImg.originalw = $("#facebox").width();
			}
			oImg.zoom = 0;
			oImg.redraw('fSubida');
			oImg.reposTop('fSubida');
			$(this).trigger("updatePositions");
		}).easydrag().bind("updatePositions",function(e,msg) {
			if (typeof(msg) != "undefined") {
				for (var key in msg) {
					$("#fSubida").css(key,( parseInt($("#fSubida").css(key)) + msg[key] )+"px");
				}
			}
			oImg.offsetX = parseInt($("#fSubida").css("left"));
			oImg.offsetY = parseInt($("#fSubida").css("top"));
		}).ondrag(function() {
			$("#fSubida").trigger("updatePositions");
		}).css("opacity","0");


		$("#gafaPuesta").bind("load",function(arg) {
			helper.stopLoading();
			$(this).fadeIn();
			oImg.originalwGafa = oImg.gafaObj.width;
			oImg.originalhGafa = oImg.gafaObj.height;

			if (firstTime) {
				$("#donePic").animate({opacity:1},1500);
				$("#noGafa").remove();
				oImg.reposTop('gafaPuesta');
				firstTime = false;
			}
			oImg.redraw('gafaPuesta');
			$(this).trigger("updatePositions");
		}).easydrag().bind("updatePositions",function(e,msg) {
			if (typeof(msg) != "undefined") {
				for (var key in msg) {
					$(this).css(key,( parseInt($(this).css(key)) + msg[key] )+"px");
				}
			}

			oImg.offsetXGafa = parseInt($("#gafaPuesta").css("left"));
			oImg.offsetYGafa = parseInt($("#gafaPuesta").css("top"));

			$("#frotateLeft").css({top:(oImg.offsetYGafa)+'px',left:(oImg.offsetXGafa-24) +'px'});
			$("#frotateLeftmini").css({top:((oImg.offsetYGafa)+25)+'px',left:(oImg.offsetXGafa-24) +'px'});
			$("#frotateRight").css({top:(oImg.offsetYGafa)+'px',left:((oImg.offsetXGafa+$("#gafaPuesta").width())) +'px'});
			$("#frotateRightmini").css({top:((oImg.offsetYGafa)+25)+'px',left:((oImg.offsetXGafa+$("#gafaPuesta").width())) +'px'});

		}).ondrag(function() {
			$("#gafaPuesta").trigger("updatePositions");
		});


		$("#showControls").bind("click",function() {
			if ($("span:last",$(this)).is(":visible")) {
				$("#facebox .fAccs:not(.rots)").fadeIn();
				$("span:last",$(this)).hide();
				$("span:first",$(this)).show();
			} else {
				$("#facebox .fAccs:not(.rots)").fadeOut();
				$("span:last",$(this)).show();
				$("span:first",$(this)).hide();
			}
		});

		helper.setCursorStyle($("#gafaPuesta"));
		helper.setCursorStyle($("#fSubida"));

		$('#idFoto').uploadify({
            'uploader': './scripts/uploadify.swf',
            'script':    './'+targetPage+'?upload=true&randid='+Math.random(),
            'folder':    '/',
            'cancelImg': './img/up_cancel.png',
            'auto':true,
            wmode:'opaque',
            fileDesc:'Imágenes',
            fileExt:'*.jpg;*.JPG;*.jpeg;*.JPEG;*.png;*.PNG;*.GIF;*.gif',
            buttonText:'Sube tu foto',
            sizeLimit:2500000,
            'multi':false,
            onProgress : function(e,q,f,d) {
				if (d.percentage == 100) {
					$("#fUpload_uploading").hide();
					$("#fUpload_processing").show();
				} else {
					$("#fUPload_percent").html(d.percentage);
				}
				return false;
			},
            onSelect : function(e,queue,file) {
				$("#fUpload_processing").hide();
				$("#fUploadProgress,#fUpload_uploading").show();

				$(this).uploadifyUpload();
				return false;
			},
     		onComplete : function(e,q,f,r,d) {
     			helper.handleResponse(r);
     			$(this)._uploadifyClearQueue();
     			return false;
     		},
     		onError : function(e,queue,file,err) {
     			$("#fUploadProgress").hide();
     			$("#fUPload_percent").html("0");
     			alert("Error subiendo el fichero.\nRecuerda que la imagen no debe ser mayor que 2MB.");
	   			$(this)._uploadifyClearQueue();
     			return false;

     		}
     });


	$("#iframe_upload_wc").attr("src","about:blank").bind("load",function() {
		var content = $("body",$(this).contents()).html();
		if (content == "") return false;
		window.setTimeout(helper.stopLoading,500);
		helper.handleResponse(content);

	});

	$("#idCam").bind("click",function() {
			data = {};
			data.texto = 'Haz click en la imagen para sacar la foto.';
			data.textoSonrie = escape('Sonríe!');
			data.targetURL = './'+targetPage+'?upload=true&randid='+Math.random();
			data.targetFRAME = 'iframe_upload_wc';
			data.jsFunctionNoCam = 'helper.noCam';
			data.jsFunction = 'helper.goLoading';
			$("#sacarFoto p,#sacarFoto h2").fadeOut('fast',function() {
				swfobject.embedSWF('./scripts/webcam.swf', 'fWebcam', '320px', '260px', '9.0.24', null, data, {'quality':'high','menu':'false'});
			});

	});
	$("#donePic").bind("click",function() {
			if (oImg.id_gafaPuesta == null) return false;
			oImg.selPic("fSubida");
			oImg.selPic("");
			oImg.selPic("fSubida");
			$("#facebox .fAccs:not(.rots)").fadeOut();
			$("#controlsFinal,#cSelectlens").slideUp("slow");
			helper.goLoading("transparente");

			window.setTimeout(function() {
				oImg.editing = false;
				var data = {}

				$.each( ('zoom,zoomGafa,originalw,originalh,originalwGafa,originalhGafa,offsetX,' +
						'offsetY,offsetXGafa,offsetYGafa,rotate,id_gafaPuesta').split(","),function(i, name){
							data[name] = oImg[name];
				});
				$("#opcionesFinal").show();
				$("#sendingData").fadeIn();

				$.post('./'+targetPage+'?hash='+oImg.hash+'&process=true&randid='+Math.random(),data,function() {
					//$("#downloadingPic").fadeIn();
					$("#sendingData").fadeOut();
					window.document.location = $("#aLink").attr("href")+targetPageGafas+"/?q="+oImg.hash;
					return;
				});

			},150);

			return false;
	});

	$("#page").disableTextSelect();


});

