function toggleReport() { 
	if($('#scene img').length > 0) { 
		$('#doreport').show();
	} else { 
		$('#doreport').hide();
	}
}
function fixDragAndClip(divtofix) { 
								var basepos =  $('#scene').offset();
								var ew = $(divtofix).width();
								var eh = $(divtofix).height();
								var cx1 = Math.floor(basepos.left - ((ew / 4)*3));
								var cy1 = Math.floor(basepos.top - ((eh/4)*3));
								var cx2 = Math.floor(basepos.left + $('#scene').width() + parseInt($('#scene').css('border-left-width')) - (ew / 4));
								var cy2 = Math.floor(basepos.top + $('#scene').height() + parseInt($('#scene').css('border-top-width')) - (eh / 4));
								$(divtofix).draggable('option', 'containment', [cx1, cy1, cx2, cy2] );
								$(divtofix).clipBy({clipdiv: '#scene'});
}
function allowNudge(divtonudge) { 
	if($('body').data('nudge') == divtonudge) { 
		disableNudge();
	} else { 
		$('body').data("nudge", divtonudge);
		$(divtonudge).css({'border':'2px solid #f00','margin':'-2px 0 0 -2px'});
	}
	$('*:focus').blur();
}
function disableNudge() { 
	d = $('body').data('nudge');
	$(d).css({'border':'none','margin':'0'});
	$('body').data("nudge",'---');
	
}

function buildVars(numberVars, appendTo, extra, file) { 
	$(appendTo).empty();
	$(appendTo).load("names.php?f="+file+"&c="+numberVars+"&e="+extra);
}

function nudgeDown() { 
	d = $('body').data('nudge');
	if(d != '---') {
		o = $(d).position();
		var n = o.top + 2;
		if(n + 8 <= $('#scene').height())  {
			$(d).css({'top': n + 'px'});
		}
	}
	fixDragAndClip(d);
}

function nudgeUp() { 
	d = $('body').data('nudge');
	if(d != '---') {
		o = $(d).position();
		var n = o.top - 2;
		h = $(d).height();
		if((n + h) - 16 >= 0) { 
			$(d).css({'top': n + 'px'});
		}
	}
	fixDragAndClip(d);
}

function nudgeLeft() {
	d = $('body').data('nudge');
	if(d != '---') {
		o = $(d).position();
		var n = o.left - 2;
		w = $(d).width();
		if((n + w) - 16 >= 0) { 
			$(d).css({'left': n + 'px'});
		}
		
	}
	fixDragAndClip(d);
}

function nudgeRight() {
	d = $('body').data('nudge');
	if(d != '---') {
		o = $(d).position(); 
		var n = o.left + 2;
		if(n + 8 <= $('#scene').width()) { 
			$(d).css({'left': n + 'px'});
		}
	}
	fixDragAndClip(d);
}	
	

	
$(document).ready(function() { 
	$('#pl, #sp, #bs,#bg').val("none");
	$('#pickfont,#varfont').val(0);
	$('#bullets').data("info", {nextbullet : 0});
	$('#enemies').data("info", {nextenemy : 0});
	$('#shots').data("info", {nextshot : 0});
	$('#fliptext').hide();
	$('#exportdata, #report, #doreport').hide();
	// create initial font dropdown
	$('body').data('nudge','---');
	
	buildVars($('#pickfont option:selected').attr("variants"), '#varfont', 'Version', $('#pickfont option:selected').val());

	$(document).bind('keydown', 'down', nudgeDown);
	$(document).bind('keydown', 'up', nudgeUp);
	$(document).bind('keydown', 'left', nudgeLeft);
	$(document).bind('keydown', 'right', nudgeRight);
	$(document).bind('keydown', 'space', disableNudge);
	$('#bg').change(function() { 
		var img = $('#bg').val();
		if(img == "none") { 
			$('#scene').css({backgroundImage: 'none'});
		} else { 
			$('#scene').css({backgroundImage: 'url("'+ img + '")'});
						if($('#bg option:selected').attr("variants")) {
							$('#bgvardiv').remove();
							$('#bg').after( '<span id="bgvardiv"><br /><select id="bgvar"></select></span>');
							buildVars($('#bg option:selected').attr("variants"), '#bgvar', 'Version', $('#bg option:selected').val());
							var src = $('#scene').css('background-image');
							// gives me url(http://shmups.info/hori/imgname)
							src = src.substring(src.indexOf('/bg/'));
							src = src.replace(')','');
							src = src.replace('"','');
						
							$('#scene').css('background-image', 'url("bgoffset.php?o=0'+src +'")');
							$('#bgvar').bind('change', function(){
								var src = $('#scene').css('background-image');
								src = src.substring(src.indexOf('/bg/'));
								src = src.replace(')','');
								src = src.replace('"','');
							
								$('#scene').css('background-image', 'url("bgoffset.php?o=' + $('#bgvar option:selected').val() + src +'")');
							});
							
						} else { 
							$('#bgvardiv').remove();
						}
		}
	});		
	$('#bs').change(function(){
		var img = $('#bs').val();
		if(img == "none") { 
			$('#boss').remove();
			$('#bsvardiv').remove();
		} else { 
			$('#boss').remove();
				$('#scene').append('<img src="'+img+'" style="position: absolute;" id="boss" />');
					$(this).oneTime(300, "boss",function() { 
						if($('#bs option:selected').attr("variants")) {
							$('#bsvardiv').remove();
							$('#bs').after( '<div id="bsvardiv"><select id="bsvar"></select></div>');
							buildVars($('#bs option:selected').attr("variants"), '#bsvar', 'Version',$('#bs option:selected').val());
							var src = $('#boss').attr('src');
							$('#boss').attr('src', 'offset.php?o=0/'+src);
							$('#bsvar').bind('change', function(){
								var src = $('#boss').attr('src');
								src = src.substring(src.indexOf('/')); // get the source. 
								$('#boss').attr('src', 'offset.php?o=' + $('#bsvar').val() + src);
							});
							$(this).oneTime(300, "fixagain", function() { fixDragAndClip('#boss')});
						} else { 
							$('#bsvardiv').remove();
						}
						$(this).oneTime(300, "boss",function() {fixDragAndClip('#boss')});
						fixDragAndClip('#boss');
					});
				$('#boss').draggable({
					containment: '#scene', 
					grid: [2,2],
					drag: function() { 
						$('#boss').clipBy({clipdiv: '#scene'});
					},
					stop: function() { 
						$('#boss').clipBy({clipdiv: '#scene'});
					},
					stack: { group: '#scene img', min: 25 }	
				});				
			
			toggleReport();
			// bind a click event to the boss
			$('#boss').click(function() { 
				allowNudge('#boss');
			});
		}
	});
	$('#sp').change(function() { 
		var img = $('#sp').val();
		if(img == "none") { 
			$('#speech').remove(); 
		} else { 
			if($('#speech').length < 1) { 
				$('#scene').append('<img id="speech" style = "position: absolute" src="'+img+'"/>');
			} else { 
				$('#speech').attr('src', img);
			}
			$('#speech').draggable({ 
				containment: '#scene', 
				grid: [2,2],
				stack: { group: '#scene img', min: 25 }
			});
		}
		toggleReport();
		$('#speech').click(function() { 
			allowNudge('#speech');
		});
	});
	$('#pl').change(function() { 
		var img = $('#pl').val();
		if(img == "none") { 
			$('#player').remove();
			$('#plvardiv').remove();
		} else { 
			$('#player').remove();
			$('#scene').append('<img id="player" style = "position: absolute" src="'+img+'"/>');
			$(this).oneTime(300, "plfix",function() { 
				if($('#pl option:selected').attr("variants")) {
					$('#plvardiv').remove();
					$('#pl').after( '<div id="plvardiv"><select id="plvar"></select></div>');
					buildVars($('#pl option:selected').attr("variants"), '#plvar', 'Player',$('#pl option:selected').val());
					var src = $('#player').attr('src');
					$('#player').attr('src', 'offset.php?o=0/'+src);
					$('#plvar').bind('change', function(){
						var src = $('#player').attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#player').attr('src', 'offset.php?o=' + $('#plvar').val() + src);
					});
					$(this).oneTime(300, "fixagain", function() {
						$('#player').draggable('option', 'containment', '#scene');
					});
				} else { 
					$('#plvardiv').remove();
				}
				$(this).oneTime(300, "player",function() {fixDragAndClip('#player')});
				fixDragAndClip('#player');			
			});
			$('#player').draggable({ 
				containment: '#scene', 
				grid: [2,2],
				drag: function() { 
					$('#player').clipBy({clipdiv: '#scene'});
				}, 
				stop: function() { 
					$('#player').clipBy({clipdiv: '#scene'});
				},
				stack: { group: '#scene img', min: 25 }
			});
		}
		toggleReport();
		$('#player').click(function() { 
			allowNudge('#player');
		});
	});
	$('#addbullet').click(function() {
		if($('.bullet_class').length >= 15 ) { return false;}
		var nextbullet = $('#bullets').data("info").nextbullet + 1;
		$('#bullets').append('<div id="bulletdiv' + nextbullet + '"><label for="bulletopt'+nextbullet+'">Bullet:</label> <select id="bulletopt'+nextbullet+'">'+ $('#bullets').data("opts").boptions +'</select> <input type="button" id="delbullet'+nextbullet+'" value="X" /></div>');
		$('#scene').append('<img style = "position: absolute" class="bullet_class" src="'+ $('#bullets').data("db").defbullet +'" id="bl'+nextbullet+'" />');
		$('#bl' + nextbullet).draggable({
			containment: '#scene',
			grid: [2,2],
			drag: function() { 
				$('#bl'+nextbullet).clipBy({clipdiv: '#scene'});
			},
			stop: function() { 
				$('#bl'+nextbullet).clipBy({clipdiv: '#scene'});
			},
			stack: { group: '#scene img', min: 25 }
		});
		
		$(this).oneTime(300, "bl",function() { 
			if($('#bulletopt'+nextbullet+' option:selected').attr("variants")) { 
				$('#bulletvar'+nextbullet).remove();
				$('#bulletopt' + nextbullet).after( '<select style="width: auto;" id="bulletvar'+nextbullet+'"></select>');
				buildVars($('#bulletopt'+nextbullet+' option:selected').attr("variants"), '#bulletvar'+nextbullet, '',$('#bulletopt'+nextbullet+' option:selected').val());
				var src = $('#bl'+nextbullet).attr('src');
				$('#bl'+nextbullet).attr('src', 'offset.php?o=0/'+src);
				$('#bulletvar'+nextbullet).bind('change', function(){
					var src = $('#bl'+nextbullet).attr('src');
					src = src.substring(src.indexOf('/')); // get the source. 
					$('#bl' + nextbullet).attr('src', 'offset.php?o=' + $('#bulletvar' + nextbullet).val() + src);
				});
				$(this).oneTime(300, "fixagain", function() { fixDragAndClip('#bl'+nextbullet)});
			} else { 
				$('#bulletvar'+nextbullet).remove();
			}
			$(this).oneTime(300, 'bullet', function() {fixDragAndClip('#bl'+nextbullet)});
		});

		$('#bulletopt' + nextbullet).bind("change", function(){
			// hey, wait a .5 sec!
			
			$('#bl' + nextbullet).attr("src", $('#bulletopt'+nextbullet+' option:selected').val());
			$(this).oneTime(300, "bl",function() { 
				if($('#bulletopt'+nextbullet+' option:selected').attr("variants")) { 
					$('#bulletvar'+nextbullet).remove();
					$('#bulletopt' + nextbullet).after( '<select style="width: auto;" id="bulletvar'+nextbullet+'"></select>');
					buildVars($('#bulletopt'+nextbullet+' option:selected').attr("variants"), '#bulletvar'+nextbullet, '',$('#bulletopt'+nextbullet+' option:selected').val());
					var src = $('#bl'+nextbullet).attr('src');
					$('#bl'+nextbullet).attr('src', 'offset.php?o=0/'+src);
					$('#bulletvar'+nextbullet).bind('change', function(){
						var src = $('#bl'+nextbullet).attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#bl' + nextbullet).attr('src', 'offset.php?o=' + $('#bulletvar' + nextbullet).val() + src);
					});
				} else { 
					$('#bulletvar'+nextbullet).remove();
				}
				$(this).oneTime(300, 'bullet', function() { fixDragAndClip('#bl'+nextbullet)});
			});
		});
		$('#delbullet' + nextbullet).bind("click", function(){
			$('#bl' + nextbullet).remove();
			$('#bulletdiv' + nextbullet).remove();
			toggleReport();
		});
		$('#bullets').data("info", {nextbullet: nextbullet});
		toggleReport();
		$('#bl' + nextbullet).click(function() { 
			allowNudge('#bl' + nextbullet);
		});
	});
	$('#addenemy').click(function() {
		if($('.enemy_class').length >= 15 ) { return false;}

		var nextenemy = $('#enemies').data("info").nextenemy + 1;
		$('#enemies').append('<div id="enemydiv' + nextenemy + '"><label for="enemyopt'+nextenemy+'">Enemy:</label> <select id="enemyopt'+nextenemy+'">'+ $('#enemies').data("opts").eoptions +'</select> <input type="button" id="delenemy'+nextenemy+'" value="X" /></div>');
		$('#scene').append('<img style = "position: absolute" class="enemy_class" src="' + $('#enemies').data("db").defenemy +'" id="enemy'+nextenemy+'" />');
		$('#enemy' + nextenemy).draggable({
			containment: '#scene', 
			grid: [2,2],
			drag: function() { 

				$(this).clipBy({clipdiv: '#scene'});
			},
			stop: function() { 
				$(this).clipBy({clipdiv: '#scene'});
			},
			stack: { group: '#scene img', min: 25 }
		});
		$(this).oneTime(300, "enemydrag",function() { 
			// okay, .5 of a second later, let's check for variants.
				if($('#enemyopt' + nextenemy + ' option:selected').attr("variants")) {
					$('#enemyvar'+nextenemy).remove();
					$('#enemyopt' + nextenemy).after( '<select style="width: auto;" id="enemyvar'+nextenemy+'"></select>');
					buildVars($('#enemyopt'+nextenemy+' option:selected').attr("variants"), '#enemyvar'+nextenemy, '',$('#enemyopt'+nextenemy+' option:selected').val());
					var src = $('#enemy'+nextenemy).attr('src');
					$('#enemy'+nextenemy).attr('src', 'offset.php?o=0/'+src);
					$('#enemyvar'+nextenemy).bind('change', function(){
						var src = $('#enemy'+nextenemy).attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#enemy' + nextenemy).attr('src', 'offset.php?o=' + $('#enemyvar' + nextenemy).val() + src);
					});
					$(this).oneTime(300, "fixagain",function() { fixDragAndClip('#enemy'+nextenemy)});
				} else { 
					$('#enemyvar' + nextenemy).remove();
				}
				$(this).oneTime(300, 'enemy',function() {  fixDragAndClip('#enemy'+nextenemy)});
				
		});

				
		$('#enemyopt' + nextenemy).bind("change", function(){
			$('#enemy' + nextenemy).attr("src", $('#enemyopt'+nextenemy+' option:selected').val());
				if($('#enemyopt' + nextenemy + ' option:selected').attr("variants")) {
					$('#enemyvar'+nextenemy).remove();
					$('#enemyopt' + nextenemy).after( '<select style="width: auto;" id="enemyvar'+nextenemy+'"></select>');
					buildVars($('#enemyopt'+nextenemy+' option:selected').attr("variants"), '#enemyvar'+nextenemy, '',$('#enemyopt'+nextenemy+' option:selected').val());	
					var src = $('#enemy'+nextenemy).attr('src');
					$('#enemy'+nextenemy).attr('src', 'offset.php?o=0/'+src);
					$('#enemyvar'+nextenemy).bind('change', function(){
						var src = $('#enemy'+nextenemy).attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#enemy' + nextenemy).attr('src', 'offset.php?o=' + $('#enemyvar' + nextenemy).val()  + src);
					});
				} else { 
					$('#enemyvar'+nextenemy).remove();
				}
			$(this).oneTime(300, "enemydrag",function(){fixDragAndClip('#enemy'+nextenemy)});
		});
		$('#delenemy' + nextenemy).bind("click", function(){
			$('#enemy' + nextenemy).remove();
			$('#enemydiv' + nextenemy).remove();
			toggleReport();
		});
		$('#enemies').data("info", {nextenemy: nextenemy});
		toggleReport();
		$('#enemy' + nextenemy).click(function() { 
			allowNudge('#enemy'+ nextenemy);
		});
	});
	$('#textopt').click(function() { 
		if($('#tx').length < 1) { 
			$('#scene').append('<img id="tx" style="position: absolute;" />');
			 $('#tx').attr('src','rotate.php?img=r|/fontgen/arcade.php/y-'+$('#pickfont').val()+'/z-'+$('#varfont').val()+'/dbl-2/cs-0.0.0/x-'+ $('#labeltext').val());
			$('#tx').draggable({
				containment: '#scene',
				grid: [2,2],
				stack: { group: "#scene img", min: 25}
			});
			$('#textopt').val("Remove Text");
			$('#fliptext').show();
		} else { 
			$('#tx').remove();
			$('#textopt').val("Add Text");
			$('#fliptext').hide();
		}
		toggleReport();
		$('#tx').click(function() { 
			allowNudge('#tx');
		});
	});
	$('#random').click(function() {
		// ask for a random name!
		var first = ['Grad','Star', 'Laser', 'Thunder', 'Sky', 'Air', 'Last', 'Mystic', 'Space', 'Omega','Bio','Alien', 'Dragon'];
		var second = ['ius','-Type',' Force', ' Fire', ' Riders', ' Blast'];
		var third = ['',' Special', ' DX', ' II', ' 3', ' Delta'];
		var pre =['', 'Super ', 'Ultra ', 'Mega '];
		
		out = pre[Math.floor (Math.random() * pre.length)];
		out = out + first[Math.floor (Math.random() * first.length)];
		out = out + second[Math.floor (Math.random() * second.length)];
		out = out +third[Math.floor (Math.random() * third.length)];
		$('#labeltext').val(out);
		if($('#tx').length > 0) { 
			$('#tx').attr('src','rotate.php?img=r|/fontgen/arcade.php/y-'+$('#pickfont').val()+'/z-'+$('#varfont').val()+'/dbl-2/cs-0.0.0/x-'+ $('#labeltext').val());
		}
	});
	$('#random').trigger('click');
	$('#pickfont').change(function() {
		if($('#tx').length > 0) { 
			$('#tx').attr('src','rotate.php?img=r|/fontgen/arcade.php/y-'+$('#pickfont').val()+'/z-1/dbl-2/cs-0.0.0/x-'+ $('#labeltext').val());
		}
		buildVars($('#pickfont option:selected').attr("variants"), '#varfont', 'Version', $('#pickfont option:selected').val());
		$('#varfont').val(0);
		$('#varfont').trigger('change');
	});
	$('#varfont').change(function() {
		if($('#tx').length > 0) { 
			$('#tx').attr('src','rotate.php?img=r|/fontgen/arcade.php/y-'+$('#pickfont').val()+'/z-'+$('#varfont').val()+'/dbl-2/cs-0.0.0/x-'+ $('#labeltext').val());
		}
	});
	$('#labeltext').blur(function() {
		if($('#tx').length > 0) { 
			$('#tx').attr('src','rotate.php?img=r|/fontgen/arcade.php/y-'+$('#pickfont').val()+'/z-'+$('#varfont').val()+'/dbl-2/cs-0.0.0/x-'+ $('#labeltext').val());
		}
	});
	$('#fliptext').click(function() {
		if($('#tx').attr('src').charAt(15) == 'r') {
			$('#tx').attr('src',$('#tx').attr('src').replace("img=r","img=l"));
		} else { 
			$('#tx').attr('src',$('#tx').attr('src').replace("img=l","img=r"));
		}
	});
	$('#addshot').click(function() {
		if($('.shot_class').length >= 5 ) { return false;}
		var nextshot = $('#shots').data("info").nextshot + 1;
		$('#shots').append('<div id="shotdiv' + nextshot + '"><label for="shotopt' +nextshot+ '">Option:</label> <select id="shotopt' +nextshot+ '">'+ $('#shots').data("opts").psoptions+ '</select> <input type="button" id="delshot' +nextshot+ '" value="X" /></div>');
		$('#scene').append('<img style = "position: absolute" class="shot_class" src="'+ $('#shots').data("db").defshot +'" id="shot'+nextshot+'" />');
		
		$('#shot' + nextshot).draggable({
			containment: '#scene',
			grid: [2,2],
			drag: function() {
				$('#shot'+nextshot).clipBy({clipdiv: '#scene'});
			},
			stop: function() { 
				$('#shot'+nextshot).clipBy({clipdiv: '#scene'});
			},
			stack: { group: '#scene img', min: 25 }
		});
		$('#shotopt' + nextshot).bind("change", function(){
			$('#shot' + nextshot).attr("src", $('#shotopt'+nextshot+' option:selected').val());
			if($('#shotopt' + nextshot + ' option:selected').attr("variants")) {
				$('#shotvar' + nextshot).remove();
					$('#shotopt' + nextshot).after( '<select style="width: 50px;" id="shotvar'+nextshot+'"></select>');
					buildVars($('#shotopt'+nextshot+' option:selected').attr("variants"), '#shotvar'+nextshot, '',$('#shotopt'+nextshot+' option:selected').val());
					var src = $('#shot'+nextshot).attr('src');
					$('#shot'+nextshot).attr('src', 'offset.php?o=0/'+src);
					$('#shotvar'+nextshot).bind('change', function(){
						var src = $('#shot'+nextshot).attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#shot' + nextshot).attr('src', 'offset.php?o=' + $('#shotvar' + nextshot).val() + src);
					});
				} else { 
					$('#shotvar' + nextshot).remove();
				}
			$(this).oneTime(300, "shotdrag",function() { fixDragAndClip('#shot'+nextshot)});
		});
		$('#delshot' + nextshot).bind("click", function(){
			$('#shot' + nextshot).remove();
			$('#shotdiv' + nextshot).remove();
			toggleReport();
		});
		$(this).oneTime(300, "shotdrag",function() { 
			if($('#shotopt' + nextshot + ' option:selected').attr("variants")) {
					$('#shotvar' + nextshot).remove();
					$('#shotopt' + nextshot).after( '<select style="width: 50px;" id="shotvar'+nextshot+'"></select>');
					buildVars($('#shotopt'+nextshot+' option:selected').attr("variants"), '#shotvar'+nextshot, '',$('#shotopt'+nextshot+' option:selected').val());
					var src = $('#shot'+nextshot).attr('src');
					$('#shot'+nextshot).attr('src', 'offset.php?o=0/'+src);
					$('#shotvar'+nextshot).bind('change', function(){
						var src = $('#shot'+nextshot).attr('src');
						src = src.substring(src.indexOf('/')); // get the source. 
						$('#shot' + nextshot).attr('src', 'offset.php?o=' + $('#shotvar' + nextshot).val() + src);
					});
					$(this).oneTime(300, "fixagain", function() {fixDragAndClip('#shot'+nextshot)});
				} else { 
					$('#shotvar' + nextshot).remove();
				}
		fixDragAndClip('#shot'+nextshot);

		});
		$('#shots').data("info", {nextshot: nextshot});
		toggleReport();
		$('#shot' + nextshot).click(function() { 
			allowNudge('#shot' + nextshot);
		});
	});
	
	$("#doreport").hover(function() { 
			$(this).attr("src","/fontgen/arcade.php/y-aura/dbl-4/z-15/x-Generate It!");
		},function() { 
			$(this).attr("src","/fontgen/arcade.php/y-aura/dbl-4/z-4/x-Generate It!");
		});
	$('#doreport').click(function(){
		var plpos = $('#player').position();
		var basepos = $('#scene').position();
		var bg = $('#scene').css('background-image');
		bg = bg.replace('url("','');
		bg = bg.replace('")','');
				bg = bg.replace('url(','');
		bg = bg.replace(')','');
		var output = 'bg=' + bg;
		$('#report').append();
		$('#scene img').each(function(i) { 
			var bpos = $(this).position();
			output = output + '&i[' + this.id  + ']='+ $(this).attr("src") + '&x['+this.id+']=' + Math.floor(bpos.left - basepos.left - 1) + '&y['+this.id+']=' + Math.floor(bpos.top - basepos.top - 1) + '&z['+$(this).css('z-index')+']=' + this.id;
			
		});
		output = $.base64Encode(output);
		$('#exportdata').val(output);
		$('#export').submit();
	});

});
