$( function() {
	//var btnUpload = $('#upload-btn');
	
	var file1 = $('#file1');
	var imgPlaceholder = $('#imgPlaceholder');
	
	bindToRemove(file1);
	
	if(customColor == 1) {
		switchColorOptions(true);
	}
	
	if($('#remove').size() == 1) {
		$(file1).hide();
	}
	
	$('#new-lens').click(function () {
		switchColorOptions(true);
		return false;
	});
	
	
	onPfChanged($("#pf"));

	new AjaxUpload(file1, {
		action : '/add-photo/upload',
		name : 'uploadfile',
		onSubmit : function(file, ext) {
	
		if (!(ext && /^(jpg|png|jpeg)$/.test(ext))) {
			imgPlaceholder.text("Povolené typy obrázků jsou - jpg, png, jpeg");
				return false;
			}
		
			imgPlaceholder.html('<span class="add-photo-loading">Nahrávám obrázek&hellip;</span>');
			$(file1).hide();

			$('#continue-btn').attr('src', '/images/continue-btn-inactive.png');
			$('#continue-btn').attr('disabled', 'disabled');
		},
		
		onComplete : function(file, ret) {

			if(ret != 'ERROR') {
				ret = ret.substring(1, ret.length - 1);
				out = '<img src="/upload/photos/original/' + ret + '" /><br/><a href="#" id="remove">Odstranit</a>';
				imgPlaceholder.html(out);
				bindToRemove(file1);
				$('#continue-btn').attr('src', '/images/continue-btn.png');
				$('#continue-btn').attr('disabled', '');
			} else {
				imgPlaceholder.text('Během nahrávání fotky došlo k chybě');
			}
		}
	});
	
	$("#pf").change( function () { onPfChanged(this); } );

});

function switchColorOptions(state) {

	if(state) {
		$('#pf').after('<input type="text" name="pf" value="' + pf + '" /><input type="hidden" name="customColor" value="1" /> <a href="#" id="back">Zpět</a>');
		$('#color').after('<input type="text" name="color" value="' + color + '"/>');
		
		$('#new-lens').hide();
		$('#pf').hide();
		$('#color').hide();
		
		$('#back').click(function() {	
			switchColorOptions(false);
			return false;
		});
		
	} else {
		$('#new-lens').show();
		$('#pf').show();
		$('#color').show();
		
		$('*[name=pf]').eq(1).remove();
		$('*[name=color]').eq(1).remove();
		$('*[name=customColor]').remove();
		$('#back').remove();
	}
}

function onPfChanged(obj) {		
	pfId = $(obj).val();
	
	sel = $('#color').get(0);
	sel.options.length = 0;

	for(lensColorId in lensesJson[pfId].colors) {
		newOption = new Option(lensesJson[pfId].colors[lensColorId], lensColorId);

		try { sel.add(newOption, sel.options[sel.options.length]); }
		catch(ex) { sel.add(newOption); }
		
		if(selectedColor == lensColorId) {
			sel.selectedIndex = sel.options.length - 1;
		}
		
	}
}

function bindToRemove(file1) {
	$('#remove').click(function() {	
		$.getJSON(
			'/add-photo/remove', 
			null,
			function(json) { $('#imgPlaceholder').html(json); $(file1).show(); }
		);	
		return false;
	});
}	
	
	
	
	
	
	
	
	

