function parseGifts() {
	var selected_gifts = [];
	$('#gifts :checked').each(function () {
		selected_gifts.push(
			new RegExp(/\d+/g).exec($(this).attr('id'))
			);
	});
	$('#selected-gifts-input').val(selected_gifts.toString());
}
function thumb_slide(obj) { 
	obj.count = 0;
	var direction, w, currentPosition;
	if (obj.size() > 4) {
		$('#product-extra-images').mouseenter(function () {
			$('.thumbs-controls').show();
		});
		$('#product-extra-images').mouseleave(function () {
			$('.thumbs-controls').hide();
		});

		w = Math.max(obj.outerWidth() * obj.size(), 340);
		$('.thumbs').css({width: w});
		$('.thumbs-controls button').click(function () {
			if ($(this).attr("class") === 'prev') {
				direction = -1;
			} else if ($(this).attr("class") === 'next') {
				direction = 1;
			}
			if (obj.count + direction >= 0 && obj.count + direction <= obj.size() - 4) {
				obj.count += direction;
				currentPosition = parseInt($('.thumbs').css('left'), 10);
				$('.thumbs').animate({left: currentPosition + (84 * -direction)});
			}
			if (obj.count > 0) {
				$('.prev').show();
			} else {
				$('.prev').hide();
			}
			if (obj.count < obj.size() - 4) {
				$('.next').show();
			} else {
				$('.next').hide();
			} 
		});
	}
}
function image_change(src) {
	var pattern, filename, filepath;
	pattern = /[^\/]*$/;
	filename = pattern.exec(src);
	filepath = $('#product-image img').attr('src').replace(pattern, '');
	$('#product-image img').attr('src', filepath + filename);
}
function dim(target) {
/* CURRENT SELECTED ELEMENT(s) FULL OPACITY WHILE OTHERS dimMED */
	if ($(target).has('input:checked').size() === 0) {
		$(target).has('input').find('img').stop().fadeTo('normal', 1);
	} else {
		$(target).has('input:checked').find('img').stop().fadeTo('normal', 1);
		$(target).has('input:not(:checked)').find('img').stop().fadeTo('normal', 0.3);
	}
}
// function removeExtraItem(instant) {
/* HELPER FUNCTION FOR GIFTS CHECK / UNCHECK BEHAVIOUR 
	if (e.find('.gift').size() > 5) {
		f = e.find('.gift input:not(:checked)').last().closest('.gift')
		f.fadeOut('fast', function() {
			f.detach();
			f.prependTo(ex).show();
		})
		if (instant) {
			f.stop(false,true);
		}
	}
}*/
function ticketCalcTotal() {
	var totalAmount, ivaAmount;
	$('#summary .last-child').removeClass('last-child');
	$('#summary tr:last-child').addClass('last-child');
	totalAmount = 0;
	ivaAmount = 0;
	$('#summary .price-value').each(function () {
		if (!isNaN(parseInt($(this).text(), 10))) {
			totalAmount += parseInt($(this).text(), 10);
		}
	});
	totalAmount = Math.round(totalAmount);
	ivaAmount = (totalAmount - (totalAmount / 1.22));
	$('#price-total').text('$ ' + formatNumber(totalAmount, 2));
	$('#iva').text(formatNumber(ivaAmount, 2));
}
function ticketAddItem(source, title, value, promo) {
	var newitem;
	if ($('.' + source).size() > 0) {
		newitem = $('.' + source);
	} else {
		newitem = $('#summary tbody tr:last-child').clone().appendTo('#summary tbody').hide();
		$(newitem).find('del').remove();
	}
	
	$('#summary:animated').stop();
	$(newitem).removeClass();
	$(newitem).addClass(source);
	$(newitem).find('.product-name').text(title);
	$(newitem).find('.price-value').text(value);
	$(newitem).show();
	ticketCalcTotal();
}
function ticketRemoveItem(target) {
	$('#summary:animated').stop();
	$(target).fadeOut('normal', function () {
		$(target).remove();
		ticketCalcTotal();
	});
}
function setCombos(state, zone, time) {
	var a, b, prev_state, prev_zone, prev_date, prev_time, time_options, time_filter, pattern, pattern2, result, deliveryPrice, messageType, itemPrice, singleItemValue;
	prev_state = $('select#delivery_state').val();
	prev_zone = $('select#delivery_zone').val();
	prev_date = $('select#delivery_date').val();
	prev_time = $('select#delivery_time').val();

	$('#delivery-time-wrapper div.special').hide();
	
	if (state !== '') {
		$('#delivery_zone *').remove();
		a = $('#delivery_zone-dummy option[data-sc-state=' + state + ']');
		b = $('#delivery_zone-dummy .all');
		$('#delivery_zone').append(a.clone());
		$('#delivery_zone').append(b.clone());
		$('#delivery .state-custom').filter(':not(.' + state + ')').hide();
		$('#delivery .state-custom.' + state).show();
		zone = $('select#delivery_zone').val();
		a = b = null;
	}	
	
	if (zone !== '')  {
		$('#delivery_date *').remove();
		a = $('#delivery_date-dummy option[data-sc-zone=' + zone + ']');
		b = $('#delivery_date-dummy option[data-sc-zone=all]');
		$('#delivery_date').append(a.clone());
		$('#delivery_date').append(b.clone());
	}

	if (time !== '') {
		time_options = parseInt($('select#delivery_zone').find('option').filter(':selected').attr('data-sc-time'), 10);
		time_filter = parseInt($('select#delivery_date').find('option').filter(':selected').attr('data-sc-time-filter'), 10);

		switch (time_options) {
		case 1:
			pattern = parseInt('1111', 2);
			break;
		case 2:
			pattern = parseInt('1110', 2);
			break;
		default:
			pattern = parseInt('0000', 2);
		}
	
		switch (time_filter) {
		case 1:
			pattern2 = parseInt('0010', 2);
			break;
		case 2:
			pattern2 = parseInt('0100', 2);
			break;
		case 3:
			pattern2 = parseInt('1110', 2);
			break;
		default:
			pattern2 = parseInt('1111', 2);
		}
	
		result = (pattern & pattern2);
		if (result === 0) {
			$('#delivery-time-wrapper').hide();
		} else {
			$('#delivery-time-wrapper').show();
		}
		$('#delivery_time *').remove();
		$('#delivery-time-wrapper select').removeAttr('name');
		if (result >> 3) {
			$('#delivery_time').append($('#delivery_time-dummy option[value="4-anytime"]').clone());
		}
		if (((result & parseInt('0100', 2)) >> 2)) {
			$('#delivery_time').append($('#delivery_time-dummy option[value="2-morning"]').clone());
		}
		if (((result & parseInt('0010', 2)) >> 1)) {
			$('#delivery_time').append($('#delivery_time-dummy option[value="3-afternoon"]').clone());
		}
		if ((result & parseInt('0001', 2))) {
			$('#delivery_time').append($('#delivery_time-dummy option[value="1-special"]').clone());
		}
		if ($('#delivery_time option').size() > 0) {
			$('#delivery_time').attr('name', $('#delivery_time').attr('id'));
		}
		a = b = null;

	}
	if ($('select#delivery_state option[value=' + prev_state + ']').size() > 0) {
		$('select#delivery_state').val(prev_state);
	}
	if ($('select#delivery_zone option[value=' + prev_zone + ']').size() > 0) {
		$('select#delivery_zone').val(prev_zone);
	}
/*	
	if ($('select#delivery_date option[value=' + prev_date + ']').size() > 0) {
		$('select#delivery_date').val(prev_date);
	};
*/
	if ($('select#delivery_time option[value=' + prev_time + ']').size() > 0) {
		$('select#delivery_time').val(prev_time);
	}
	deliveryPrice = 0;
	$('#delivery .system-message > div').hide();
	$('#delivery select:enabled option:selected').each(function () {
		messageItem = $(this).attr('data-sc-msg-type');
		messageItem = (messageItem === null || messageItem === '') ? undefined : messageItem;
		itemPrice = $(this).attr('data-sc-price');
		if (isNaN(parseInt(itemPrice,10)) || itemPrice < 0) {
			itemPrice = 0;
		}
		deliveryPrice = Math.max(parseInt(itemPrice, 10), deliveryPrice);
		if (messageType === undefined) {
			messageType = messageItem;
		}
	});
	customMessage = $('#delivery .system-message ' + '.' + messageType);
	customItems = $('#delivery .' + messageType);
	customItems.show();
	if (customMessage.size() > 0) {
		$('#delivery .system-message .standard').hide();
		$('#delivery .system-message ' + '.' + messageType).show();
	} else if (deliveryPrice > 0) {
		$('#delivery .system-message .standard').show();
	}
	$('#delivery .system-message').filter(':visible').find('.price').text(deliveryPrice)
	$('#delivery select:enabled').each(function () {
		$(this).find(' ~ span').remove();
		if ($(this).find('option').size() === 1) {
			singleItemValue = $(this).find('option').text();
			$(this).after('<span>' + singleItemValue + '</span>');
			$(this).hide();
		} else {
			$(this).show();
		}
	});
	$('#delivery-time-wrapper div select').each(function() {
		$(this).removeAttr('name');
	})
	$('#delivery-time-wrapper div:visible select').each(function() {
		$(this).attr('name', $(this).attr('id'));
	})

	ticketAddItem('delivery_cost', 'Costo de envío', formatNumber(deliveryPrice, 2));
}
function chosenGift(target) {
	var title, price;
	dim('#gifts .gift'); // CHANGE OPACITY WHEN DONE
	if (!$(target).attr('checked')) {
		// uncheck
		ticketRemoveItem($('#summary .' + $(target).attr('id')));
	} else {
		// check
		title = $(target).closest('.gift').attr('title');
		price = Math.round((new RegExp(/\d+/g).exec($(target).closest('.gift').find('.price').text())));
		ticketAddItem($(target).attr('id'), title, formatNumber(price, 2));
	}
}
function photoComplete(filename, msg) {
	var imgObject, posX, posY;
	msg = (msg === '' || msg === null || msg === undefined) ? 'intente nuevamente' : msg;
	$('#in-the-gift .loading').hide();
	imgObject = $('#in-the-gift-image');
	imgObject.one('load', function () {
		posX = $('#in-the-gift').find('.photo-preview').width() / 2 - $(this).width() / 2;
		posY = $('#in-the-gift').find('.photo-preview').height() / 2 - $(this).height() / 2;
		$(this).css({'left' : posX, 'top' : posY});
		imgObject.fadeIn('slow');
	});
	imgObject.attr('src', '');
	if (filename != null) {
		$('#in-the-gift .cancel-button span').text('quitar foto');
		imgObject.hide();
		imgObject.attr('src', filename);
		$('#in-the-gift .status').hide();
		// to-do show image
	} else {
		$('#in-the-gift-input-file').prependTo('.in-the-gift-upload');
		$('#in-the-gift-input-file').attr('value', '');
		
		$('#in-the-gift :animated').stop();
		$.ajax({url: 'includes/uploadtest.asp?action=delete', async: false});
		$('#in-the-gift .upload-button').show();
		$('#in-the-gift .cancel-button').hide();
		$('#in-the-gift .status').show();
		$('#in-the-gift-image').attr('src', '');
		$('#in-the-gift-image').hide();
		$('#in-the-gift .status').text('Agregue una foto a su tarjeta');
		$('#in-the-gift .loaderror').text(msg);
		$('#in-the-gift .loaderror').show();
		
	}
}
function photoUploading(e) {
	var imgObject;
	$('#in-the-gift .loaderror').hide().text('');
	imgObject = $('#in-the-gift-image');
	$('#in-the-gift .loading').fadeIn();
	$('#in-the-gift .status').text('grabando foto');
	$('#in-the-gift .cancel-button span').text('cancelar');
	
	$('#in-the-gift .upload-button').hide();
	$('#in-the-gift .cancel-button').show();
}
function addStepNumbers() {
	var i;
	i = 1;
	$('div.fieldset').filter(':not(#summary)').find('h3').each(function () {
		$(this).css('backgroundImage', 'url(images-pd/' + i + '.jpg)');
		i++;
	});
}

$(document).ready(function () {
	$('#delivery_date-dummy option[value="20100903"]').attr('data-sc-time-filter', 3);

	var segment_date = ($('#delivery').attr('data-sc-segment-date') == 'afternoon') ? 0.5 : 0;
	// me devuelve si puedo poner en la tarde o mañana ej: tarde, 0.5
	var prod_time = parseFloat($('#product').attr('data-sc-production-time'))
	// el tiempo de produccion, ej: 1 dias
	var ready_day = prod_time + segment_date;
	// prod time + segment = 1.5 dias [+1 default] = 2.5

	if (prod_time > 0) {
		$('#delivery_date-dummy option[data-sc-day]').each(function() {
			if ($(this).attr('data-sc-day') <= ready_day) {
				// all (< 2) => remove
				$(this).remove();
			}
			if ($(this).attr('data-sc-day') == Math.ceil(ready_day)) {
				if (Math.ceil(ready_day) - ready_day > 0) {
					// if 2 - int(2) > 0 then switch day 2
					if ($(this).attr('data-sc-time-filter') > 0){
						$(this).remove();
					} else {
						$(this).attr('data-sc-time-filter', 1)
					}
				}
			}
		})
	}
	
	var current_state, current_zone, current_time;
	$('#in-the-gift-cancel-button').click(function () {
		photoComplete();
	});
	$('#in-the-gift-input-file').change(function () {
		photoUploading();
		$(this).appendTo('body').css('marginTop', '-90000');
		$(this).upload('includes/uploadtest.asp', function (res) {
			try {
				res = jQuery.parseJSON(res);
				if (res.result === 1 && res.filename !== "") {
					photoComplete(res.filename);
				} else {
					photoComplete(null, res.msg);
				}
			}
			catch (e) {
				photoComplete(null);
			}
		}, 'text');
	});
	addStepNumbers();
	ticketCalcTotal();
	/* DELIVERY OPTION */
	current_state = $('select#delivery_state').val();
	current_zone = $('select#delivery_zone').val();
	current_time = $('select#delivery_time').val();
	setCombos(current_state, current_time);
	
	$('select#delivery_state').change(function (e) {
		current_state = $('select#delivery_state').val();
		current_zone = ''; //$('select#delivery_zone').val()
		current_time = $('select#delivery_time').val();
		setCombos(current_state, current_zone, current_time);
	});
	
	$('select#delivery_zone').change(function (e) {
		current_state = ''; //$('select#delivery_state').val()
		current_zone = $('select#delivery_zone').val();
		current_time = $('select#delivery_time').val();
		setCombos(current_state, current_zone, current_time);
	});

	$('select#delivery_date').change(function (e) {
		current_state = '';//$('select#delivery_state').val()
		current_zone = '';//$('select#delivery_zone').val()
		current_time = $('select#delivery_time').val();
		setCombos(current_state, current_zone, current_time);
	});

	$('select#delivery_time').change(function (e) {
		current_state = '';
		current_zone = ''; // $('select#delivery_zone').val()
		current_time = ''; // $('select#delivery_time').val()
		setCombos(current_state, current_zone, current_time);
	});
	/* END OF DELIVERY OPTIONS */

	/* INITIALIZATION BUTTONS */
	$('#form button[type=submit]').click(function (e) {
		parseGifts();
	}).mousedown(function () {
		$(this).addClass('continue-green-active');
	}).mouseup(function () {
		$(this).removeClass('continue-green-active');
	}).mouseout(function () {
		$(this).removeClass('continue-green-active');
	});

	/* UPLOAD */
/*
	if ($('#in-the-gift-upload-button').size() > 0) {
		new AjaxUpload('in-the-gift-upload-button', {
			action: 'upload.txt',
			onSubmit : function(file , ext){
	            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
	                alert('Error: invalid file extension');
	                return false;
	            }else{
								photoUploading();
	            }
			},
			onComplete : function(file, response){
				var filename = $.ajax({url: 'product_details_upload.asp?action=upload&fileName=' + file, async: false}).responseText;
				photoComplete(filename);
			}
		});
	}
*/
	$('#in-the-gift-input-file').css('opacity', 0.0001);

	$('#in-the-gift button.upload-button').mousedown(function () {
		$(this).addClass('action-black-active');
	}).mouseup(function () {
		$(this).removeClass('action-black-active');
	});
	
	$('#in-the-gift-upload-button, #in-the-gift .photo-preview').click(function () {
		if (!$.browser.msie) {
			$('#in-the-gift-input-file').click();
		}
	});
	
	/* END UPLOAD */
	/* END OF INITIALIZATION BUTTONS */

	$('.view-more').click(function () {
		var selected, extrafill;
		// OPEN/CLOSE GETTS AND RE-ARRANGE ELEMENTS //
		if ($('#gifts-container-extra').is(':visible'))  {	// IF CONTAINER IS CLOSING, RE-ARRANGE
			/* GET SELECTED ELEMENTS, and OPTIONALLY, EXTRA non-selected ones */
			selected = $('#gifts .gift input:checked').closest('.gift').detach();
			extrafill = $('#gifts .gift input:not(:checked):lt(' + (5 - parseInt(selected.size(), 10)) + ')').closest('.gift').detach();
			$('.gift').prependTo('#gifts-container-extra'); // MOVE NON CHOSEN GIFTS INTO EXTRA CONTAINER
			$('#gifts-container').append(selected);
			$('#gifts-container .gift input').attr('checked', true); // FIX IE6 CHECKBOX STATUS RESET
			$('#gifts-container').append(extrafill);
		}
		/* OPEN/CLOSE */
		$('html, body').animate({scrollTop: $('#gifts').offset().top}, 'normal');
		$('#gifts-container-extra').slideToggle();
		$(this).toggleClass('up');
	});
	$('#gifts .gift :checkbox').filter(':checked').each(function () {
		chosenGift(this);
	});
	
	$('#gifts .gift :checkbox').change(function () {
		chosenGift(this);
	});

	$('.card-preview label > img').click(function (e) {
		// MAKE FUNCTION BEHAVE AS A LABEL -- WITH FIX INTERNET EXPLORER
		e.preventDefault();
		$(this).closest('.card-preview').find(':radio').each(function () {
			$(this).attr('checked', true);
			dim('#personalization-card .card-preview');
		});
	});
	$('.gift').mouseover(function (e) {
		$(this).has('input:not(:checked)').find('img').stop().fadeTo('normal', 1);
	});
	$('.gift').mouseout(function (e) {
		if ($('.gift').has('input:checked').size() > 0 ) {
			$(this).has('input:not(:checked)').find('img').stop().fadeTo('normal', 0.3);
		}
	});
	$('.gift label > img').click(function (e) {
		e.preventDefault();
		// MAKE FUNCTION BEHAVE AS A LABEL -- WITH FIX INTERNET EXPLORER
		$(this).closest('.gift').find(':checkbox').each(function () {
			$(this).attr('checked', !$(this).is(':checked'));
			chosenGift(this);
		});
	});
/* MESSAGE CARDS */
	/* AUTOGROW */
	$("textarea#textarea-card-message").autoResize({
		limit: 152,
		extraSpace: 0,
		animate: false,
		onResize : function () {
			var h = 152 - $(this).height();
			$('#textarea-card-message').css({
				paddingTop: h / 2,
				paddingBottom: h / 2
			});
		}
	});
	$("textarea#textarea-card-message").change().hide().show();
	
	/* END OF AUTOGROW */
	$('#personalization-card .card-preview :radio').click(function (e) {
				dim('#personalization-card .card-preview');
			});
	if ($('#personalization-card .card-preview').has('input:checked').size() > 0) {
		dim('#personalization-card .card-preview');
	}
/* END OF MESSAGE CARDS */

	/* THUMBS SLIDER */
	thumb_slide($('.thumbs button:visible'));
	$('.thumbs button:visible').click(function () {
		var src;
		src = $(this).find('img').attr('src');
		image_change(src);
	});

	$('#no-signature').click(function () {
		if ($(this).is(':checked')) {
			$('#personalization fieldset').animate({opacity: 0.3});
			$('#personalization fieldset input').not('.no-signature').attr('disabled', true);
			$('#personalization fieldset textarea').attr('disabled', true);
		} else {
			$('#personalization fieldset').animate({opacity: 1});
			$('#personalization fieldset input').not('.no-signature').attr('disabled', false);
			$('#personalization fieldset textarea').attr('disabled', false);
		}
	});

/* END OF THUMBS SLIDER */

	$("#productForm").validate({
		errorClass: "warning",
		focusInvalid: false,
		errorPlacement: function (error) {
			error.appendTo("#form-error-list");
		},
		rules: {
			textarea_card_message: {
				required: true ,
				maxlength: 200
			},
			card_type: {
				required: true
			}
		},
		messages: {
			textarea_card_message: {
				required: "No se olvide de escribir un mensaje para la tarjeta."
			},
			card_type: {
				required: "Seleccione uno de los dise&ntilde;os de tarjeta en la parte superior antes de continuar."
			}
		}
	});
	$('.unavailable').each(function() {
		$(this).find('input').attr('disabled', true);
		$(this).find('select').attr('disabled', true);
		$(this).find('textarea').attr('disabled', true);
		$(this).find('label').attr('disabled', true);
		$(this).find('*').unbind('click');
		
		$(this).fadeTo('normal', 0.3);
	});
	$("#productForm").submit(function (e) {
		var validate = $("#productForm").validate().form();
		if (validate) {
			if ($('#logged').val() === "") {
				$.nyroModalManual({
					url: 'ajaxLogin.asp'
				});
				return false;
			}
		} else {
			return false;
		}
	});
});

