$(document).ready(function() {
	$('.license_song').live('click', function() {
		addToCart($(this).attr('id'), $(this));
	});
});

function addToCart(song_id, clicked) {

	$('body').append('<div id="bg_overlay"></div>' +
		'<div style="display: none" id="license_popup">' +
		'<h3>Select license type...</h3>' +
		'<div class="close_button close">close</div>' +
		'<table>' +
		'   <tr>' +
		'       <td class="type">Web Music<p>Website background music</p></td>' +
		'       <td>$49.00</td>' +
		'       <td class="license"><div id="1">&nbsp;</div></td>' +
		'   </tr><tr>' +
		'       <td class="type">Wedding<p>Wedding film or wedding photo slideshow</p></td>' +
		'       <td>$99.00</td>' +
		'       <td class="license"><div id="2">&nbsp;</div></td>' +
		'   </tr><tr>' +
		'       <td class="type">Non-Profit<p>Non-profit film or slideshow</p></td>' +
		'       <td>$99.00</td>' +
		'       <td class="license"><div id="3">&nbsp;</div></td>' +
		'   </tr><tr>' +
		'       <td class="type">Small Business<p>Small business promotional film</p></td>' +
		'       <td>$199.00</td>' +
		'       <td class="license"><div id="4">&nbsp;</div></td>' +
		'   </tr><tr>' +
		'       <td class="type">Film Festival<p>Film festival submission</p></td>' +
		'       <td>$199.00</td>' +
		'       <td class="license"><div id="5">&nbsp;</div></td>' +
		'   </tr>' +
		'</table>' +
		'<div class="close_button continue">Continue Shopping</div>' +
		'<div class="close_button checkout"><a href="/cart/">Check Out</a></div>' +
		'</div>'
	);

	$('#license_popup .license div').each(function() {
		if (isSongInCart(song_id, $(this).attr('id'))) {
			$(this).addClass('incart');
		}
	});

	$('.close_button').click(function() {
		$('#license_popup').slideUp('fast', function() {
			$(this).remove();
			$('#bg_overlay').remove();
		});
	});
	$('#license_popup .license div').click(function() {
        $(this).html('&nbsp;').addClass('loading');
		$.ajax({
            url: baseURL + '/wp-admin/admin-ajax.php',
            type:     'POST',
            dataType: 'json',
            data:     'action=my_ajax_cart_add&song_id=' + song_id + '&option=' + $(this).attr('id'),
            success: function(data) {
                if (data.added) {
					$('.count').html(parseInt($('.count').html()) + 1);
					$('#license_popup').slideUp('fast', function() {
						$(this).remove();
						$('#bg_overlay').remove();
					});
					clicked.removeClass('loading').addClass('incart');
					// Add to header pulldown
					var license = '';
					switch (data.license){
						case '1':
							license = 'Web Music'; 
							break;
						case '2':
							license = 'Wedding'; 
							break;
						case '3':
							license = 'Non-profit'; 
							break;
						case '4':
							license = 'Small Business'; 
							break;
						case '5':
							license = 'Film Festival'; 
							break;
						default:
							license = 'Unknown'
							break;
					}
					var structure = [
                        '<li class="song" id="' + song_id + '">',
                            '<span class="nav_title">' + data.name + '</span> by ',
                            '<span class="nav_artist">' + data.artist + '</span>',
                            '<div class="trash"></div><br />',
                            '<small class="item"><span class="nav_license" id="' + data.license + '">' + license + '</span> License</small>',
                        '</li>'
					];
					$(structure.join('')).appendTo('#songcart');
				}
            },
            error: function(){
				$('#license_popup').slideUp('fast', function() {
					$(this).remove();
					$('#bg_overlay').remove();
            		alert('An error has occured. Please contact the site administrator.');
				});            	
            }
        });
	});

	$(window).resize(function() {
		$('#license_popup').center();
	});
	$(window).scroll(function() {
		$('#license_popup').center();
	});
	$('#license_popup').center();
	$('#license_popup').slideDown('fast');	

}

/**
 * Checks if a song is in the cart preview UL dropdown element
 */
function isSongInCart(id, option){
	if ($('#player_iframe').size() != 0) {
		var cart = $('#player_iframe').contents().find('#songcart');
	} else {
		var cart = $.find('#songcart');
	}
    if ($(cart).find('li[id="' + id + '"]').size() > 0) {
        // If a product option is not defined and product is found
        if (option == undefined) {
            return true;
        // If a product option is defined search for it in the cart
        } else {
            var inCart = false;
            $(cart).find('li[id="' + id + '"]').each(function() {
                if ($(this).find('.nav_license').attr('id') == option) {
                    inCart = true;
                }
            });
            return inCart;
        }
    } else {
        return false;   
    }
}

$('#songcart').find('.trash').live('click', function(){
	
    var parent = $(this).parents('li.song'),
        id = parent.find('small.item').attr('id');
	
	$('.license_song[id="' + $(this).parents('.song').attr('id') + '"]').removeClass('incart');
	
    $.ajax({
        url:  '/wp-admin/admin-ajax.php',
        type: 'POST', 
        data: 'action=my_ajax_cart_remove&item=' + id,
        success: function(data){
        	$('.count').html(parseInt($('.count').html()) - 1);
            parent.fadeOut('fast', function(){
                $(this).remove(); 
            });
        }
    });
});

function checkoutNow() {
    $("#cart_bottom").hide();
    $("#checkout").show();
}

function hidePayment() {
    $(".payment_option").hide();
}

function submitPay() {
    $("#errors").hide();
    $("#loading").show();
    $('#submitButton').attr("disabled", true);
	$.post("/cart/submit_pay", $("form").serializeArray(),
		function(data) {
		    $("#loading").hide();
			if (data.errors != undefined) {
				var msg = "<ul>";
				for (i in data.errors) {
				   msg += "<li>" + data.errors[i] + "</li>";
				}
				$("#errors").html(msg);
				$("#errors").show();
				$('#submitButton').attr("disabled", false);
			} else if (data.success) {
			   $("#success").show();
			   $("#checkout").hide();
			   $("#cart").hide();
			}
		}, 'json');
}

function checkField(select) {
    $('#submitButton').attr("disabled", true);
    $("form").submit();
}

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    vertical:true, // booleen, center vertical
                    withScrolling:true, // booleen, take care of element inside scrollTop when minX < 0 and window is small or when window is big
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);
