
Smirk = {

	popIndex: 0,	
	smirks: 0,

	// callback from every smirk swf when it is loaded
	smirkIsLoaded: function(domId) {
		//console.log("loaded: " + domId);
	},

	processingSmirk: function(smirkId) {
		var sid = "smirk-"+smirkId;	
		document.getElementById(sid).processingIcon();	
	},

	finishedSmirk: function(smirkId) {
		document.getElementById("smirk-"+smirkId).getIcon(smirkId);		
		Smirk.updateCurrent(smirkId) 
	},
	
	processingNewSmirk: function(smirkId) {
		//console.log("processing NEW");
		document.getElementById("smirk-000").processingIcon(); // this fails on a new page
	},

	finishedNewSmirk: function(smirkId) {
		//console.log("finished NEW");
		$("#btn-new").css({zIndex: "5"}).addClass("inactive").removeClass('cancel');
		//console.log("about to repop");
		Smirk.updateCurrent(smirkId); 
		Smirk.repopulate("new", smirkId);
	},

	smirkClicked: function(smirkId) {

		$("#iid-display").empty().append("iid is: " + smirkId);

		// show green border on selected icon
		$(".icon").each(function() {	

			var t = $(this).attr("id");
	
			if (t && t != "smirk-"+smirkId) {
				document.getElementById(t).unselect();
			}

		});

		
		document.getElementById("maker-swf").switchMode('edit');
		document.getElementById("maker-swf").getIcon(smirkId);
		$("#btn-new").css({zIndex: "5"}).addClass("inactive").removeClass('cancel');
		$("#smirk-000").remove();
		
		// populate SHARE info
		var embd = '<object width="160" height="160" type="application/x-shockwave-flash" data="http://mysmirks.com/swf/smirk.swf"><param name="allowScriptAccess" value="always"/><param name="flashvars" value="uuid='+smirkUuid+'&loop=1"/><embed src="http://mysmirks.com/swf/smirk.swf" type="application/x-shockwave-flash" width="160" height="160" allowscriptaccess="always" flashvars="uuid='+smirkUuid+'&loop=1"></embed></object>';
		
		$("#icon-embed-code").attr("value", embd);
			
		$.getJSON("http://mysmirks.com/iid_version.php?u="+smirkUuid+"&i="+smirkId, function(j) {
				$("#icon-gif").replaceWith('<img id="icon-gif" src="http://mysmirks.com/images/no-smirk.jpg" width="80" height="80" alt="my icon"/>');
				$("#icon-gif").addClass("uuid-is-"+j.iid);
				
				Smirk.smirkAnimatorStart();
		});
		
		
	},

	updateCurrent: function(newCurrent) {
		
		var oldCurrent = smirkIid;
		var uid = smirkUuid;
		if (newCurrent) {
			
			try { // this will fail on NEW
				$(".current-sm").remove();
				var l = $("#smirk-"+newCurrent).position().left - 19;
				var t = $("#smirk-"+newCurrent).position().top - 21;
				var flag = $("<img src='/images/current-sm.png'>")
					.css({
						position: "absolute",
						top: t,
						left: l,
						width: 110,
						height: 79,
						zIndex: 100
					})
					.addClass("current-sm")
				$("#smirk-"+newCurrent).parent().append(flag);				
			}
			catch(er){
				//console.log("died  on label")
			}
			var nc = newCurrent;
			
			$.getJSON("/update_smirk_jax.php?iid="+newCurrent, function(d) {
				document.getElementById("maker-swf").getIcon(newCurrent);
				
				$(Smirk.smirks).each(function(i) {
	
					if (this.smirk_mode == newCurrent) {
						smirkIid = newCurrent;
						$("#iid-display").empty().append("iid is: " + newCurrent);
						$("#twit-link").attr('href', 'http://twitter.com/home?status=I\'m feeling ' + this.blerb + ' http://mysmirks.com/' + smirkLogin);
						//$("#icon-gif").attr('src', this.thumb);
					
						//$("#download-frame a:first").attr('href', this.thumb);
						//$("#icon-buddy a:first").attr('href', "aim:BuddyIcon?src=" + this.thumb);
					
						$.getJSON("http://mysmirks.com/iid_version.php?u="+uid+"&i="+newCurrent, function(j) {
							$("#icon-gif").addClass("uuid-is-"+j.iid);
							Smirk.smirkAnimatorStart();
						});
					
					}
						
				});
				
				
				setTimeout(function() {
					try {
						document.getElementById("smirk-" + oldCurrent ).showAsCurrent(false);
					} catch(er){}
					try {
						document.getElementById("smirk-"+nc).showAsCurrent(true);
					} catch(er){}
				}, 500);
				
	
			});
		}
		
	},


	deleteIcon: function(id) {

		if (confirm("This is insane!\n\nAre you *sure* you want to delete this Smirk?\n\n")) {
			
			$.getJSON("/delete_jax.php?iid="+id, function(d) {
			
				
					// call to maker to show the new current				
					document.getElementById("maker-swf").getIcon(smirkIid);
					Smirk.repopulate(Smirk.popIndex);  // or maybe a specific delete flag?
					
					$(Smirk.smirks).each(function(i) {
		
						if (this.smirk_mode == smirkIid) {
							$("#icon-gif").attr('src', this.thumb);
							$("#download-frame").attr('href', this.thumb);
							$("#icon-buddy a:first").attr('href', "aim:BuddyIcon?src=" + this.thumb);
						}
							
					});
				
				
			});
			
		}
		
	},

	
 	loadEmUp: function() {

		// console.log("starting load em up");
		
		var baseIid = smirkIid || 0;
	
		// Embed the maker swf 
		var flashvarz = {
			uuid: smirkUuid,
			iid: baseIid,
			domId: "maker-swf"
		};
		var params = {allowScriptAccess: "always", wmode: "transparent"};
		var attributes = { id: "maker-swf", name: "maker-swf" };
		swfobject.embedSWF("http://mysmirks.com/swf/maker-v4.swf", "maker-swf", 320, 420, "9.0.0", "http://mysmirks.com/swf/express_install.swf", flashvarz, params, attributes);
    
    Smirk.smirks = Array();
		$.getJSON("/gimmie_smirks_jax.php?u="+smirkUuid, function(d) {
			
			// console.log("back with " + d.length);
			// this is super brittle but just to get it happening:
			Smirk.smirks = d;
			
			var pop = 0;
			$(Smirk.smirks).each(function(i) {
		
				if (this.smirk_mode == smirkIid) {
					Smirk.popIndex = pop;
				}
				
				if (i%6 == 0 && i > 0) {
					pop += 6;	
				}
				
			});
			
			Smirk.populate(Smirk.popIndex);
			
			
			if (smirkIid == 0) { // TBD yank
				Smirk.populate(Smirk.popIndex);
			}
			
			
			// slide the nav to the selected page
		
			var popPage = Math.ceil(Smirk.popIndex / 6);
			//console.log("starting offset: " + popPage);
			if (popPage > 3) {
				
				navPos = (popPage - 3);
				var navOffset = 89 * navPos;
				$("#icon-nav-items").animate({left: "-="+navOffset+"px"});
				
				//console.log("offsetting: " + navOffset);
			}
				
			// render default links, etc to the current selected icon
			var uid = smirkUuid;
			var smirkId = smirkIid;
			// populate SHARE info
			var embd = '<object width="160" height="160" type="application/x-shockwave-flash" data="http://mysmirks.com/swf/smirk.swf"><param name="allowScriptAccess" value="always"/><param name="flashvars" value="uuid='+uid+'&loop=1"/><embed src="http://mysmirks.com/swf/smirk.swf" type="application/x-shockwave-flash" width="160" height="160" allowscriptaccess="always" flashvars="uuid='+uid+'&loop=1"></embed></object>';
			
			$("#icon-embed-code").attr("value", embd);
				
			$(Smirk.smirks).each(function(i) {
		
					if (this.smirk_mode == smirkIid) {
					
						//$("#icon-gif").attr('src', this.thumb);
						//$("#download-frame a:first").attr('href', this.thumb);
						//$("#icon-buddy a:first").attr('href', "aim:BuddyIcon?src=" + this.thumb);
					
						
						$.getJSON("http://mysmirks.com/iid_version.php?u="+uid+"&i="+smirkId, function(j) {
							$("#icon-gif").addClass("uuid-is-"+j.iid);
							Smirk.smirkAnimatorStart();
						});
						
					
					}
					
			});
			
		});
			
	},


	repopulate: function(from, iid, isRollover) {
		// console.log("repop called");
		Smirk.smirks = Array();
		$.getJSON("/gimmie_smirks_jax.php?u="+smirkUuid, function(d) {
			
			Smirk.smirks = d;
			
			// callback from Flash will just have "new" as the from value
			// calculate that to the last frame of icons
			if (from == "new") {
			
				from = Math.floor((Smirk.smirks.length-1) / 6) * 6;
				// console.log("new icon, from set to: " + from);
				
				Smirk.updateCurrent(iid); 
				Smirk.smirkClicked(iid);
				
			}
			
			Smirk.popIndex = from;
			
			if (isRollover) Smirk.populate(from, true);
			else Smirk.populate(from);
			
		});
	},
	
	
	buildNav: function(selectedPage) {
	
		$("#icon-nav-items").empty();
		
		if (Smirk.smirks.length > 5) {
		
			$(".nav-arrow").show();
				
			// this should be more graceful, straight positioning now	
			var shareOffset = Math.floor(Smirk.smirks.length / 24); 
			shareOffset = (shareOffset * 75) + 470;
			$("#share").css(shareOffset); // starts at 470
			
			
			for (var t=0; t<1; t++) { // build a few passes to test
			
				$(Smirk.smirks).each(function(i) {
		
					if (i%6 == 0) {
							
							// populate the current s-page
							var to = Math.min(i + 6, Smirk.smirks.length); 
							$("#icon-nav-items").append(
								$("<div class='s-page' id='s-page-"+t+"-" +i+"'></div>").click(function() {
									
									Smirk.repopulate(i);
								})
							);
							
							// indicate current
							if (i == selectedPage) {
								$("#s-page-"+t+"-"+i).addClass("current-page");
								
							}
							
							$(Smirk.smirks).each(function(x) {
								if (x >= i && x < to) {
									
									$("#s-page-"+t+"-"+i).append('<img class="s-page-preview" src="'+this.thumb+'">');
									
								}
							});
						
				
					}
				
					//.s-page-preview
					
				});		
			
			}
			
		}
		else { // less than 5, let's hide the nav arrows
			$(".nav-arrow").hide();
		}
		
	},

	

	populate: function(from, isRollover) {
	
		// console.log("in populate");
		
		if (Smirk.smirks.length == 1) {
			$(".step-4").show();
			$(".step-4").animate({opacity: 1}, 1000);
		}
		else {
			$(".step-4").hide();
			$(".step-4").css({opacity: 0});
		}
		
		// RENDER current smirks:
		var to = Math.min(from + 6, Smirk.smirks.length);
		var makeupPlaces = (from+6) - to;
		
		//console.log("to: " + to + " and makup: " + makeupPlaces);
		
		// case where we are on a new page from hitting the new button...
		if (isRollover) makeupPlaces = 6;
		
		
		
		$("#icon-container").empty();
		
			if (Smirk.smirks.length < 1) { // handle case where user has no smirks for whatever reason
				
				$("#icon-container").append('<div class="icon" id="smirk-000">');
				var flashvarz = { uuid: smirkUuid, iid: 1, domId: "smirk-000", lonely: true };
				var paramz = {allowScriptAccess: "always", wmode: "transparent"};
				var attributes = { id: "smirk-000", name: "smirk-000", "class": "icon" };
				swfobject.embedSWF("http://mysmirks.com/swf/icon-v2.swf", "smirk-000", 120, 120, "9.0.0", "http://getyoursmirkon.com/swf/express_install.swf", flashvarz, paramz, attributes);
				
				makeupPlaces = 5; // fill in the rest
				
				// kick the maker over to record
				$("#btn-new").css({zIndex: "5"}).toggleClass("inactive").toggleClass('cancel');
				
				setTimeout(function() {
					document.getElementById("maker-swf").switchMode('new');
				}, 700);
				

			
			}
			else {
				$(Smirk.smirks).each(function(i) {
					
					//// console.log("count: " + i)
					if (i >= from && i < to) {
						$("#icon-container").append('<div class="icon" id="smirk-' + this.smirk_mode + '">');
	
						var flashvarz = { uuid: smirkUuid, iid: this.smirk_mode, domId: "smirk-"+this.smirk_mode };
						if (Smirk.smirks.length == 1) flashvarz.lonely = true;
						
						
						var paramz = {allowScriptAccess: "always", wmode: "transparent"};
						var attributes = { id: "smirk-"+this.smirk_mode, name: "smirk-"+this.smirk_mode, "class": "icon" };
						
						swfobject.embedSWF("http://mysmirks.com/swf/icon-v2.swf", "smirk-"+this.smirk_mode, 120, 120, "9.0.0", "http://getyoursmirkon.com/swf/express_install.swf", flashvarz, paramz, attributes);
										
					}
				});
			}
			
			// indicate the current, 
			// delay this call
			
			
			
			var sid = "smirk-" + smirkIid;
			var tm = setInterval(function() {
				
				try
				{
					document.getElementById(sid).showAsCurrent(true);
					clearInterval(tm);
					
					$(".current-sm").remove();
					var l = $("#"+sid).position().left - 19;
					var t = $("#"+sid).position().top - 21;
					var flag = $("<img src='/images/current-sm.png'>")
						.css({
							position: "absolute",
							top: t,
							left: l,
							width: 110,
							height: 79,
							zIndex: 100
						})
						.addClass("current-sm")
					$("#"+sid).parent().append(flag);
					
					
					
					// console.log('killing loop');
				}
				catch(er) {
					// console.log('not loaded yet');
					clearInterval(tm);
				}
				
			}, 1200);
			
			// fill in placeholders
			for (var q=0; q<makeupPlaces; q++) {
				$("#icon-container").append('<div class="icon placeholder">');
				//console.log("appending " + q)
			}
			

			Smirk.buildNav(from);


      
	}, // end populate
	
	
	buildPublicNav: function(selectedPage, smrks) {
	
		$("#icon-nav-items").empty();
		
		if (smrks.length > 5) {
		
			// console.log("populate public Nav");
			
			// position the share block
			// this should be more graceful, straight positioning now
			
			var shareOffset = Math.floor(smrks.length / 24);
			shareOffset = (shareOffset * 75) + 470;
			$("#share").css(shareOffset); // starts at 470
			
			
			for (var t=0; t<1; t++) { // build a few passes to test
			
				$(smrks).each(function(i) {
						
					if (i%6 == 0) {
						
							
							// populate the current s-page
							var to = Math.min(i + 6, smrks.length); 
							$("#icon-nav-items").append(
								$("<div class='s-page' id='s-page-"+t+"-" +i+"'></div>").click(function() {
									
									//$(this).append('<div class="fly-out">');
									//$('.fly-out').animate({top: -300, left: -100, width: 300, height: 200});
									
									Smirk.populatePublic(i);
								})
							);
							
							// indicate current
							if (i == selectedPage) {
								$("#s-page-"+t+"-"+i).addClass("current-page");
							}
							
							$(smrks).each(function(x) {
								if (x >= i && x < to) {
									
									$("#s-page-"+t+"-"+i).append('<img class="s-page-preview" src="'+this.thumb+'">');
									
								}
							});
						
					}
				
					//.s-page-preview
					
				});		
			
			}
		}
		else { // less than 5, let's hide the nav arrows
			$(".nav-arrow").hide();
		}
		
	},
	
	populatePublic: function(from) {

		
		// Embed the maker swf 
		var flashvarz = {
			uuid: publicUser.uuid,
			iid: publicUser.mood,
			domId: "maker-swf",
			prettyName: publicUser.login,
			startMode: 'play'
		};
		var params = {allowScriptAccess: "always", wmode: "transparent"};
		var attributes = { id: "maker-swf", name: "maker-swf" };
		swfobject.embedSWF("http://mysmirks.com/swf/maker-v4.swf", "maker-swf", 320, 420, "9.0.0", "http://mysmirks.com/swf/express_install.swf", flashvarz, params, attributes);
	
		
		var frm = from;
	
		// console.log("populate public for " + publicUser.login);
		
		$.getJSON("/gimmie_smirks_public_jax.php?p_smirk_uuid="+publicUser.uuid, function(d) {
			
			Smirk.smirks = d;
			// console.log("found " + d.length + " public smirks");
			
			if (frm == "new") {
				if (Smirk.smirks.length % 6 == 0) frm = Smirk.smirks.length - 6;
				else frm = 6 * Math.floor(Smirk.smirks.length / 6);
			}
			
			
			// RENDER current smirks:
			var to = Math.min(frm + 6, d.length);
			var makeupPlaces = (frm+6) - to;
			
			$("#icon-container").empty();
			
			$(d).each(function(i) {
				
				//// console.log("count: " + i)
				if (i >= frm && i < to) {
					$("#icon-container").append('<div id="smirk-' + this.smirk_mode + '" class="icon">');
		
					var flashvarz = {
						uuid: publicUser.uuid,
						iid: this.smirk_mode,
						domId: "smirk-" + this.smirk_mode,
						href: "javascript:document.getElementById('iid-display').innerHTML=\'iid is: " + this.smirk_mode + "';document.getElementById('maker-swf').getIcon("+this.smirk_mode+");",
						target: "_self"
					};
					var params = {allowScriptAccess: "always", wmode: "transparent"};
					var attributes = { id: "smirk-" + this.smirk_mode, name: "smirk-" + this.smirk_mode, "class": "icon" };
					
					swfobject.embedSWF("http://mysmirks.com/swf/smirk.swf", "smirk-" + this.smirk_mode, 120, 120, "9.0.0", "http://mysmirks.com/swf/express_install.swf", flashvarz, params, attributes);
					
				}
			});
			
			// fill in placeholders
			for (var q=0; q<makeupPlaces; q++) {
				$("#icon-container").append('<div class="icon placeholder">');
			}
			
			Smirk.buildPublicNav(frm, d);
			
		});
	
	}, // end populate public


	nameHunt: function(formElementId) {

		var u = $("#"+formElementId).attr('value');
		$.getJSON("http://mysmirks.com/name_hunter.php?u="+u, function(j) {
			if (j.stat == 'taken') {
			
				alert('Some loser is already using that user name, try another?');
				$("#"+formElementId).focus();
			}	
		});
	
	},
	
	parseNvClasses: function(classValue) {
		var nvPairs = "{";
		var cls = classValue.split(/\s+/);
		$(cls).each(function() {
			if (this.indexOf("-is-") > 0) { // regex?
				var a = this.split("-is-");
				if (nvPairs.length > 1) nvPairs += ",'"+a[0]+"' : '"+a[1]+"'";
				else nvPairs += "'"+a[0]+"' : '"+a[1]+"'";
			}
		});
		nvPairs += "}";
		//alert(nvPairs)
		return eval('('+nvPairs+')');
	},
	
	animating: false,
	
	smirkAnimatorStart: function() {
		
		if (Smirk.animating) {
			clearInterval(Smirk.animating);
			Smirk.animating = false;
		}
		
		// #icon-gif
		//var anim = false;
		var currentFrame = 1;
		var nv = Smirk.parseNvClasses($("#icon-gif").attr("class"));
		
		$("#icon-gif").attr("src", "http://mysmirks.com/vids/"+smirkUuid+"/"+nv.uuid+"1.jpg");
		$("#download-frame").attr('href', "http://mysmirks.com/vids/"+smirkUuid+"/"+nv.uuid+"1.jpg");
		$("#icon-buddy a:first").attr('href', "aim:BuddyIcon?src=http://mysmirks.com/vids/"+smirkUuid+"/"+nv.uuid+"1.jpg");
		
		$("#icon-gif").unbind("mouseover").unbind("mouseout");
		
		$("#icon-gif")
			.bind("mouseover", function() {
				if (Smirk.animating) {
					clearInterval(Smirk.animating);
					Smirk.animating = false;
				}
				var smirkFrames = 21;
				var imageObjects = new Array(); // total frames is 21 for now
				
				//alert(imageObjects.length);
				
				for (var i=0; i<smirkFrames; i++) {
					var imgStub = new Image();
					imgStub.src = "http://mysmirks.com/vids/"+smirkUuid+"/"+nv.uuid+""+(i+1)+".jpg";
					//console.log("http://mysmirks.com/vids/"+nv.uuid+""+(i+1)+".jpg")
					imageObjects.push(imgStub);
				}
				
				
				var forwards = true;
				var targetElement = this;
				
				Smirk.animating = setInterval(function() {
					if (currentFrame > smirkFrames) {
					
						currentFrame = smirkFrames - 1;
						forwards = false;
						
					}
					
					else if (currentFrame < 1) {
					
						currentFrame = 2;
						forwards = true;
						
					}
					
					//console.log('render: ' + images[currentFrame-1])
					$(targetElement).attr("src", imageObjects[currentFrame-1].src);
					$("#download-frame").attr('href', imageObjects[currentFrame-1].src);
					$("#icon-buddy a:first").attr('href', "aim:BuddyIcon?src=" + imageObjects[currentFrame-1].src);
					
					if (forwards)	currentFrame ++;
					else currentFrame --;
				
				}, 130);
			
			})
			.bind("mouseout", function() {
				
				if (Smirk.animating) {
					clearInterval(Smirk.animating);
					Smirk.animating = false;
				}
				
			})
	
	}
	

} // end Smirk



// hook in listeners on password field and other globals

$(function() {
	
	function pwListen() {
		$("#smirk-password")
			.focus(function() {
				$(this).addClass("field-focused");
				if(this.value=='Password') {
					$(this).replaceWith('<input type="password" id="smirk-password" class="field-focused" name="p" value="">');
					$("#smirk-password").focus();
					pwListen();
				}
			})
			.blur(function() {
				
				if(this.value.length < 1) {
					$(this).replaceWith('<input type="text" id="smirk-password" name="p" value="Password">');
					pwListen();
				}
				else {
					$(this).removeClass("field-focused");
				}
				
			});
	}
	
	
	$("#smirk-user")
		.focus(function() {
			$(this).addClass("field-focused");
			if(this.value=='Username') this.value='';
		})
		.blur(function() {
			$(this).removeClass("field-focused");
			if(this.value.length < 1) this.value='Username';
			
		});
	
	pwListen();	
	
	$("#smirk-submit")
		.click(function() {
			$('#smirk-password').attr('value', hex_sha1($('#smirk-password').attr('value')))
		});

});

