// bu js dokumani Siz Neyle Besleniyorsunuz icin yazilmistir. Orhan Ekici

$(function(){
	// fire it up
	step1()
})

function theCropperTool(imgUrl, tanim){
		
	// live the slider
	$('#wayOfSlider').slider({
		step:10,
		slide:function(){ resizePic($('#wayOfSlider').slider('option', 'value')) },
		change:function(){ resizePic($('#wayOfSlider').slider('option', 'value')); posControl() },
		start:killPreview
	})
	
	var imgWidth = $('#imageCropLeft img').width();
	var imgHeight = $('#imageCropLeft img').height();
	
	centerPic('imageCropLeft img:first')
	$('#imageCropLeft img').css('visibility', 'visible')
	
	// gelen height degerini kaldiralim ki resim deforme olmasin
	$('#imageCropLeft img').removeAttr('height');
	
	var minWidth = 308;
	var minHeight = 235;
	
	var pMinWidth = Math.round(minHeight * imgWidth / imgHeight);
	var pMinHeight = Math.round(minWidth * imgHeight / imgWidth);
	
	$('#wayOfSlider').slider('option', 'min', pMinWidth > minWidth ? pMinWidth : minWidth);
	$('#wayOfSlider').slider('option', 'max', $('#imageCropLeft img').width());
	$('#wayOfSlider').slider('option', 'value', $('#imageCropLeft img').width());
	
	// lets crop it baby
	$('#cropFade').css({backgroundColor:'#211409', opacity:'0.6'}) // isiklari kapatalim
	centerPic('cropperTool')
	centerCropPic('imageCropLeft img:last')
	$('#cropperTool img').draggable({ cursor: 'move', drag: equalBothPics, stop: posControl, start:killPreview })
	$('#cropperTool img, #wayOfSlider a').click(killPreview)
	
	// onizleme
	$('li#cropPreview').click(function(){
		if($(this).hasClass('on')) killPreview();
		else {
			$(this).addClass('on');
			$('#cropFade').stop().fadeTo(400, 1)
			$('#cropperTool div').fadeOut(200)
		}
	})
	
	// gimme the size man
	$('#cropSend').one("click", function(){
		$('#slider, #cropPreview, #cropBack').css('visibility', 'hidden')
		$('#cropLoad').css('top','90px')
		$('#cropSend').addClass('on')
		
		var sendData = 'image='+imgUrl+'&width='+$('#cropperTool img').width()+'&height='+$('#cropperTool img').height()+'&x='+(parseInt($('#cropperTool img').css('left')) * -1)+'&y='+(parseInt($('#cropperTool img').css('top')) * -1)+'&tanim='+tanim;
		
		$.ajax({
			url:'/image/crop',
			type:'POST',
			data:sendData,
			success:function(e){
				$('#cropLoad').css('top','-60px');
				showAlert('Teşekkürler sizin de besininiz eklendi ve onaylandıktan sonra yayınlanacaktır.', 'window.location.replace("/choice")')				
			}
		})
		//alert(
		//	$('#cropperTool img').width() + ' x ' + $('#cropperTool img').height() + '\n' +
		//	(parseInt($('#cropperTool img').css('left')) * -1) + ' x ' + (parseInt($('#cropperTool img').css('top')) * -1)
		//)
	})
}

function killPreview (){
	$('li#cropPreview').removeClass('on')
	$('#cropFade').stop().fadeTo(250, 0.6)
	$('#cropperTool div').fadeIn(100)
}

function resizePic(width){ $('#imageCropLeft img').attr('width', width); }

function centerPic(element){
	var left = (597/2) - ($('#'+element).width() / 2);
	var top = (310/2) -  ($('#'+element).height() / 2);
	$('#'+element).css({top:top+'px', left:left+'px'})
}

function centerCropPic(element){
	var left = parseFloat($('#imageCropLeft img:first').css('left')) - parseFloat($('#'+element).parent().css('left'));
	var top = parseFloat($('#imageCropLeft img:first').css('top')) - parseFloat($('#'+element).parent().css('top'));
	$('#'+element).css({top:top+'px', left:left+'px'})
}

function equalBothPics(){
	var left = parseFloat($('#cropperTool img').parent().css('left')) + parseFloat($('#cropperTool img').css('left'));
	var top = parseFloat($('#cropperTool img').parent().css('top')) + parseFloat($('#cropperTool img').css('top'));
	$('#imageCropLeft img:first').css({top:top+'px', left:left+'px'})
}

function posControl(){
	var width = parseInt($('#cropperTool img').width());
	var height = parseInt($('#cropperTool img').height());
	
	var sBottom = 235 - height;
	var sRight = 308 - width;

	var top = parseFloat($('#cropperTool img').css('top'));
	var left = parseFloat($('#cropperTool img').css('left'));
	
	if(left < sRight) left = sRight;
	if(left > 0) left = 0;
	if(top > 0) top = 0;
	if(top < sBottom) top = sBottom;
	
	getBackToPos(top, left)
}

function getBackToPos(top, left){
	$('#cropperTool img').animate({ top:top, left:left}, 250)

	var bLeft = parseFloat($('#cropperTool img').parent().css('left')) + left;
	var bTop = parseFloat($('#cropperTool img').parent().css('top')) + top;
	
	$('#imageCropLeft img:first').animate({ top:bTop, left:bLeft}, 250)
}

// ilk asama dostlar
function step1(){
	$('#content').load('/item/add_step1', function(){
		
		// input focus	
		$('#sendeGonder ul li input')
			.focus(function(){ $(this).addClass('focus').parents('li').addClass('on') })
			.blur(function(){ $(this).removeClass('focus').parents('li').removeClass('on') })
			$('#sendeGonder ul li.browse dl dd span').css({visibility:'visible', opacity:'0'})
			
		// give life to browse button
		$('#sendeGonder ul li.browse form').css({ visibility:'visible', opacity:'0' })
		$('#sendeGonder ul li.browse form input').hover(function(){ $('#sendeGonder ul li.browse dl dd span').stop().fadeTo(300,1) }, function(){ $('#sendeGonder ul li.browse dl dd span').stop().fadeTo(300,0) }).change(function(){ $('#sendeGonder ul li.browse dl dt input').val($(this).val()) })

		// email check sart
		var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

		// gonderim onceki kontroller
		$('#submitBtn a').bind("checkFormLoadNext", function(){
			if($('#sendeGonder ul li input[name="mail"]').val() == ""){ showAlert('Gerektiğinde sana ulaşabilmemiz için geçerli bir e-mail adresi girmelisin', "$('li.tbox:first input').focus()");  return false; }
			if(!$('#sendeGonder ul li input[name="mail"]').val().match(emailRegEx)){ showAlert('Gerektiğinde sana ulaşabilmemiz için geçerli bir e-mail adresi girmelisin', "$('li.tbox:first input').focus()");  return false; }
			if($('#sendeGonder ul li input[name="tanim"]').val() == ""){ showAlert('Eklediğin besin için bir tanım girmelisin', "$('li.tbox:last input').focus()");  return false; }
			if($('#sendeGonder ul li input[name="chooseFile"]').val() == ""){ showAlert('Göndermek istediğin fotoğrafı seçmelisin');  return false; }
			$('#sendeGonder ul li input[name="email"]').val($('#sendeGonder ul li input[name="mail"]').val())
			$('#submitBtn a').addClass('on').unbind('click');
			
			setLoading(1)
			
			var options = {
				url: '/image/upload_temp',
				type: 'POST',
				iframe: true,
				success: function(e){
					setLoading(0)
					
					switch (e) {
						case '-1':
							showAlert('Seçim yapabilmek ve besin ekleyebilmek için üye girişi yapman gerekiyor.')
							$('#submitBtn a').removeClass('on').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
						break;
						case '-2':
							showAlert('Besin eklemek için formu eksiksiz doldurmalısın')
							$('#submitBtn a').removeClass('on').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
						break;
						case '-3':
							showAlert('Yüklemiş olduğun resim en az 308x235 çözünürlüğünde olmalı')
							$('#submitBtn a').removeClass('on').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
						break;
						case '-4':
							showAlert("Yüklemiş olduğun resim en fazla 1 MB boyutunda olmalı")
						  $('#submitBtn a').removeClass('on').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
						break;
						case '-5':
							showAlert("Fotoğrafın .jpg, .png ya da .gif formatında olmalı")
							$('#submitBtn a').removeClass('on').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
						break;
						default:
							step2(e.split(',')[0], e.split(',')[1], e.split(',')[2], $('#sendeGonder ul li input[name="tanim"]').val())
						break;
					}
				}
			}
			$('#sendeGonder ul li.browse form').ajaxSubmit(options)
		})
		
		$('#submitBtn a').bind('click', function(){ $(this).trigger('checkFormLoadNext') })
	})
}

function step2(imgUrl, width, height, tanim){
	$('#content').prepend(
		$('<div />')
			.attr('id', 'cropContent')
			.load('/item/add_step2', function(){
				$('#imageCropLeft img').attr({ src:'/temp_upload/'+imgUrl, alt:tanim, width:width, height:height })
				$('span.tanim').text(tanim)
				$('#bendeEklesem').remove()
				$('li#cropBack a').one('click',step1)
				
				// show baslasin
				theCropperTool(imgUrl, tanim)
			})
	)
}
