﻿$(document).ready(function() {
	initCufon();
	$('ul.radio-sprite li').click(function(){
		cupSizeActivate(this);
	});
    function cupSizeActivate($target) {
	    $('.small-product, .small-product-active',$($target).parent()).toggleClass('small-product')
		                                                           .toggleClass('small-product-active');
	    $('.big-product, .big-product-active',$($target).parent()).toggleClass('big-product')
		                                                       .toggleClass('big-product-active');
		var $cupSize = $('input.cupSize', $($target).parent().parent());
		if($cupSize.val() == 'big') {
			$cupSize.val('small');
		} else {
			$cupSize.val('big');
		}
	}
	$('.box form').submit(function(f) {
		if(!$(this).hasClass('fruit-not-available')) {
			$.ajax({
				'type': 'POST',
				'url': $(this).attr('action'),
				'data': $(this).serialize(),
				'success': function(d) {
					$('#sidebar .c').html(d);
				}
			});
		}
		else
		{
			alert('Seçmiş olduğunuz meyve ya da meyveler elimizde bulunmuyor. Güncel meyve mönümüze "Bardağını Oluştur" sayfamızdan bakabilirsiniz.');
		};
		return false;
	});
	$('.add-delivery-address').submit(function(f) {
		$.ajax({
			'type': 'POST',
			'url': $(this).attr('action'),
			'data': $(this).serialize(),
			'success': function(d) {
				location.reload(true);
			}
		});
		return false;
	});
	$('.holder2 .btn-close').live('click', function() {
		$('#sidebar .c').load(this.toString());
		return false;
	});
	$('.holder2 form select').live('change', function() {
		$.ajax({
			'type': 'POST',
			'url': $(this).closest('form').attr('action'),
			'data': $(this).closest('form').serialize(),
			'success': function(d) {
				$('#sidebar .c').html(d);
			}
		});
		return false;
	});
	$('.order-form .col3 select').change(function() {
		$(this).closest('form').attr('action', function() { return this.action + '/update/'; }).submit();
	});
	$('input[name=deliveryTime]').click(function() {
		$(this).val() == 'later' ? $('.laterDeliveryInput').fadeIn('fast') : $('.laterDeliveryInput').fadeOut('fast');
	});
	$('.holder2 .btn-holder a').live('click', function() {
		if(!$('.holder2 .list li').length > 0) {
			alert('Sepetinizde hiç ürün bulunmuyor. Sipariş sayfasına devam edebilmek için lütfen ürün ekleyiniz.');
			return false;
		}
	});
	$('input[name=dateOfBirth]').datepicker({
		changeMonth: true,
		changeYear: true,
		showAnim: false,
		yearRange: '1920:2000',
		dateFormat: 'dd/mm/yy',
		dayNamesMin: ['Pa', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct', 'Pa'],
		monthNamesShort: ['Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara']
	});
	$('#ui-datepicker-div').hide();
	$('input:radio[name=deliveryAddress]:first, input:radio[name=paymentType]:first').attr('checked', 'checked');
	$('.boxes-row .heading a').colorbox({
		'innerWidth': '717px',
		'initialWidth': '317px',
		onComplete: function() {
			$('.popup-form').submit(function(f) {
				$.ajax({
					'type': 'POST',
					'url': $(this).attr('action'),
					'data': $(this).serialize(),
					'success': function(d) {
						$('#sidebar .c').html(d);
						$.fn.colorbox.close();
					}
				});
				return false;
			});
		}
	});
	$('.add-link').colorbox({
		'innerWidth': '556px',
		'innerHeight': '350px',
		onComplete: function(){
			$('.add-delivery-address').submit(function(f) {
				$.ajax({
					'type': 'POST',
					'url': $(this).attr('action'),
					'data': $(this).serialize(),
					'success': function(d) {
						location.reload(true);
					}
				});
				return false;
			});
		}
	});
	$(".btnClose, .artinContainer a").live('click', function() {
		$.fn.colorbox.close();
	});
	$('.out-of-stock, .new-cup').prepend('<div class="notify"></div>');
	$('.out-of-stock form .btn-submit').attr('disabled', 'disabled');
	$('a[href*=delete]').click(function(e) { 
		if(!confirm('Seçtiğiniz bardağı kalıcı olarak silmek üzeresiniz. Devam etmek istediğinize emin misiniz?')) {
			e.preventDefault();
		}
	});
	$('a[href*="add-to-cup"]').click(function(e) {
		var rHrefValues = $(this).attr('href').split('/');
		var placeholder = $('.left-holder .list li img:last');
		if(placeholder.length > 0) {
			placeholder.parent('li').html('<a style="background-color: #' + $(this).attr('rel') + '" href="#remove-from-cup/' + rHrefValues[1] + '"><span>' + $(this).text() + '</span></a>');
			$('.cup-prepare').append('<input type="hidden" rev="' + $(this).attr('rev') +'" name="fruits[]" value="' + rHrefValues[1] + '"/>');
			updateCupIndicator();
			updateRetailPrice();
		}
		else {
			alert('Bir bardağa en fazla ' + String($('.left-holder .list li').length) + ' porsiyon meyve ekleyebilirsiniz. Eğer yeni ekleme yapmak istiyorsanız mevcut meyvelerden birisini silmeniz gerekiyor.');
		}
		e.preventDefault();
	});
	$('a[href*="remove-from-cup"]').live('click', function(e) {
		var rHrefValues = $(this).attr('href').split('/');
		$(this).parent('li').html('<img src="' + listPlaceHolderImage + '"/>');
		$('.cup-prepare input[value=' + rHrefValues[1] + ']:first').remove();
		updateCupIndicator();
		updateRetailPrice();
		e.preventDefault();
	});
	$('form .btn-ekle').click(function() {
		var placeholder = $('.left-holder .list li img');
		if(placeholder.length == 0 && $('.cup-prepare input[name=cupName]').val().length >= 1) {
			$('.cup-prepare').submit();
		}
		else if(placeholder.length == 0 && $('.cup-prepare input[name=cupName]').val().length < 1) {
			alert('Lütfen bardağınıza bir isim veriniz. Vereceğiniz isim en az 1 karakter en fazla 12 karakter olmalıdır.');
		}
		else if(placeholder.length > 0 && $('.cup-prepare input[name=cupName]').val().length >= 1) {
			alert('Bardağı sepetinize ekleyebilmeniz için bardağınıza ' + String($('.left-holder .list li').length) + ' porsiyon meyve eklemeniz gerekiyor.');
		}
		else {
			alert('Bardağı sepetinize ekleyebilmeniz için bardağınıza ' + String($('.left-holder .list li').length) + ' porsiyon meyve eklemeniz ve bardağa bir isim vermeniz gerekiyor.');
		}
		e.preventDefault();
	});
	$('form input[name="fruits[]"], .custom-cups-prepare li').click(function() {
		updateRetailPrice(); 
	});
	var updateCupIndicator = function() {
		var placeholder = $('.left-holder .list li img');
		var maxAvailableFruitCount = $('.left-holder .list li').length;
		$('.cup-indicator:not(.price) span').text((( maxAvailableFruitCount - placeholder.length ) * ( 100 / maxAvailableFruitCount )).toFixed(0));
	}
	var updateRetailPrice = function() {
		var totalRetailPrice = 0;
		var totalCalories = 0;
		$('input[name="fruits[]"]:checked').each(function(i, v) {
			totalRetailPrice += parseFloat($(v).attr('rev').split('|')[0]);
			totalCalories += parseFloat($(v).attr('rev').split('|')[1]);
		});
		$('input[name="fruits[]"][type="hidden"]').each(function(i, v) {
			totalRetailPrice += parseFloat($(v).attr('rev').split('|')[0]);
			totalCalories += parseFloat($(v).attr('rev').split('|')[1]);
		});
		$('.cup-prepare .retail-price, .cup-indicator .calories').text(totalCalories + ' Kalori');
		var sizeCost = 0;
		if($('input.cupSize').val() == 'big') sizeCost = 1.5;
		if(totalRetailPrice >= customCupMinAmount) {
			$('.cup-prepare .retail-price, .cup-indicator .retail-price').text(String((totalRetailPrice + sizeCost).toFixed(2)) + ' TL');
		}
		else {
			$('.cup-prepare .retail-price, .cup-indicator .retail-price').text(String((customCupMinAmount + sizeCost).toFixed(2)) + ' TL');
		}
	}
	$('.btnCloseAlert').live('click', function(e) {
		$('.maAlertOverlay').hide();
		$('body').css("overflow","visible");
		e.preventDefault();
	});
	$("#twitter").tweet({
	  join_text: "auto",
	  username: "BiBardakMeyve",
	  count: 1,
	  loading_text: "Twitter yükleniyor...",
	  auto_join_text_default: "", 
	  auto_join_text_ed: "",
	  auto_join_text_ing: "",
	  auto_join_text_reply: "",
	  auto_join_text_url: ""
	});
		// Add tooltip
	var hashtags = { "Şefin Sosu":"Çilek ve Tarçın", "Sosun Şefi":"Tarçın ve Çilek" };
	
	// Search for each item
	$.each(hashtags, function(i, val) {
		// Search for each primary text
		$('*:contains(' + i + ')').each(function(){
			// Check if primary text exist
			if($(this).children().length < 1) {
				// Remove secondary text
				$(this).html( 
				   $(this).text().replace(
						' (' + val + ')'
						,'' 
				   )
				);
				// Add secondary text to primary one as a tooltip
				$(this).html( 
				   $(this).text().replace(
						i
						,'<abbr title="' + val + '">' + i + '</abbr>' 
				   )
				);
			}
		});
	});
	
});
function alert(errMsg){
	document.location.href = "#top";
	$('.maAlertOverlay').show().css({'height': $(window).height(), 'width': $(window).width()});
	$('body').css("overflow","hidden");
	$('.alertTextChange').text(errMsg);
}
function initCufon() {
	Cufon.replace('.header-text h2 span', { fontFamily: 'AauxPro-Light'});
	Cufon.replace('.header-text h2 strong', { fontFamily: 'AauxPro-Regular'});
	Cufon.replace('#header .slogan', { fontFamily: 'AauxPro-ThinItalic'});
	Cufon.replace('#footer .footer-r .phone em ', { fontFamily: 'AauxPro-Bold'});
}




