$(document).ready(function() {	
	
/*
	var updatePrice = function() {
	   var shipping = $('#destination').val();
	   
	   if(shipping == 'europe') {
	       $('#vat-container').show();
	   } else {
	       $('#vat-container').hide();
	   }
	   
	   if(shipping != undefined) {
	       shipping = shipping.split('|');
    	   var cost = Number($('#cost').text());
    	   var quantity = Number($('#quantity').val());
    	   var price = (cost + Number(shipping[1])) * quantity;
    
    	   $('#price').html(price.toFixed(2));
	   }
	}
*/
	
/*
	updatePrice();

	$('#destination,.quantity').change(function() {
        updatePrice();
	});
	$('#vat').keyup(function() {
        updatePrice();
	});
*/
    initModal();
    
	document.isTouch = ('ontouchstart' in window);
	document.touchDisabled = false;

	/* Scrolly Nav
	-------------------------------------*/
	$('#nav, ul.fire-navigation, #logo, #callout-text').localScroll();
	
	/* Preview Prints Slideshow
	-------------------------------------*/
	var $tabs = $('#slideshow').tabs({ idPrefix: 'ui-tabs-prints', fx: { opacity: 'toggle' } });	
	$('#slideshow div img').click(function() {
        var next = $tabs.tabs('option', 'selected') +1;
        if(next == $tabs.tabs('length')) {
            next = 0;
        }
        
        $tabs.tabs('select', next);
        //clearInterval(autoPlay);
	});
	
/*
	autoPlay = setInterval(function() {
        var next = $tabs.tabs('option', 'selected') +1;
        if(next == $tabs.tabs('length')) {
            next = 0;
        }
        
        $tabs.tabs('select', next);
	}, 5000);
*/
	
	/* Preview Current Issue Slideshow
	-------------------------------------*/
	var $ciTabs = $('#ci-slideshow').tabs({ idPrefix: 'ui-tabs-issue', fx: { opacity: 'toggle' } });	
	$('#ci-slideshow div img').click(function() {
        var next = $ciTabs.tabs('option', 'selected') +1;
        if(next == $ciTabs.tabs('length')) {
            next = 0;
        }
        
        $ciTabs.tabs('select', next);
        clearInterval(autoPlay);
	});
	
	autoPlay = setInterval(function() {
        var next = $ciTabs.tabs('option', 'selected') +1;
        if(next == $ciTabs.tabs('length')) {
            next = 0;
        }
        
        $ciTabs.tabs('select', next);
	}, 5000);

	/* Modal Boxes
	-------------------------------------*/
	if(!$('body').hasClass('mobile')) {
    	//Get the screen height and width
    	var maskHeight = $(window).height(); 
    	var maskWidth = $(window).width();
    	          
    	//Set the modal to proper size and position above viewport
    	$('.modal').css('margin-top', '-' + maskHeight + 'px');
    	$('.modal').css('width', maskWidth);
    	$('.modal').css('height', maskHeight - 1); // account for the bottom border
	}

	
	$('a.modal-trigger').click(function(e) {
        if($('body').hasClass('mobile')) {
            return true;
        }
        
		// Cancel the link behavior
		e.preventDefault();

        if($(this).hasClass('clicked')) {
            return;
        }

		// Get the id from the anchor
		var button = this;
		var id = $(button).attr('href');
		
		if(id == '#cart' && $(button).attr('data-id')) {
            var buttonText = $(button).text();
            $(button).width($(button).width()).height($(button).height()).text('').addClass('clicked');

            $.get('/shop/order/add', {
                type: $(this).attr('data-type'),
                id: $(this).attr('data-id'),
                method: 'ajax'
            }, function(data) {
                // Disable scroll on iPad
                $('body').scrollTo({top: 0, left: 0}, 300);
        		controlTouch();

                $(id).html(data);

        		// Make Magic!
        		if ( $(id).css('margin-top') == '0px' ) {
        			$(id).animate({
        				marginTop: '-' + $(window).height() + 'px'
        			}, 330 ).removeClass('open');
        		} else {
        			$(id).animate({ 
        				marginTop: '0px'
        			}, 330 ).addClass('open');
        		}
        		
        		initModal();
        		
        		$(button).text(buttonText).removeClass('clicked');
            });
		
		} else {
    		// Make Magic!
    		if ( $(id).css('margin-top') == '0px' ) {
    			$(id).animate({
    				marginTop: '-' + $(window).height() + 'px'
    			}, 330 ).removeClass('open');
    		} else {
    			$(id).animate({ 
    				marginTop: '0px'
    			}, 330 ).addClass('open');
    		}		
		}	
	});
	
	initModal();
	
	$('.sold-out').click(function(e) {
	   e.preventDefault();
	});
	
	/* Misc
	-------------------------------------*/
	$(window).bind("resize", resizeWindow);
});

function resizeWindow(e) {
	var newWindowHeight = $(window).height();
	var newWindowWidth = $(window).width();
	
	$.each( $('.modal'), function() {
		$(this).css('height', newWindowHeight - 1 ); // account for border
		$(this).css('width', newWindowWidth );
		$(this).css('margin-top', '-' + newWindowHeight);
	});
}

function preventScroll(e) {
    e.preventDefault();
}

function controlTouch() {
    if(document.isTouch) {
        if(document.touchDisabled) {
            document.removeEventListener('touchmove', preventScroll, false);
            document.touchDisabled = false;
        } else {
            document.addEventListener('touchmove', preventScroll, false);
            document.touchDisabled = true;
        }
    }
}

function initModal() {
	// if close button is clicked
	$('.close, #logo').click(function(e) {
        if($('body').hasClass('mobile')) {
            return true;
        }

		e.preventDefault();
		
		$('.open').animate({
			marginTop: '-' + $(window).height() + 'px'
		}, 330 ).removeClass('open');
		// Enable scroll on iPad
		controlTouch();
	});
	
	$('.remove').click(function(e) {
        if($('body').hasClass('mobile')) {
            return true;
        }
        
        e.preventDefault();
        var cartItem = $(this).parents('ol');
        
		if($(this).attr('data-id')) {
            $.getJSON('/shop/order/remove', {
                id: $(this).attr('data-id'),
                method: 'ajax'
            }, function(data) {                
                cartItem.fadeOut('normal', function() {
                    cartItem.remove();
                    updatePrice();
                    
                    if($('.quantity').length == 0) {
                        $('.close').click();
                    }
                });
                
                $('#destination').children().remove();
                
                $(data).each(function(i, item) {
                    $('#destination').append('<option value="'+item.id+'" '+(item.selected == 'true' ? 'selected' : '')+'>'+item.name+'</option>');
                });
            });
        }        

	});

    updatePrice();
    
	$('#destination').change(function() {
        $.get('/shop/order/update-region', {
            destination: $(this).val(),
            method: 'ajax'
        });

        updatePrice();
	});
	
	$('.quantity').change(function() {
        $.get('/shop/order/update-quantity', {
            quantity: $(this).val(),
            id: $(this).attr('data-id'),
            method: 'ajax'
        });
        
        $.getJSON('/shop/order/update-shipping', {
            method: 'ajax'
        }, function(data) {                
            $('#destination').children().remove();
            
            $(data).each(function(i, item) {
                $('#destination').append('<option value="'+item.id+'" '+(item.selected == 'true' ? 'selected' : '')+'>'+item.name+'</option>');
            });
            
            updatePrice();
        });

        //updatePrice();
	});
	$('#vat').keyup(function() {
        updatePrice();
	}).change(function() {
        $.get('/shop/order/update-vat', {
            vat: $(this).val(),
            method: 'ajax'
        });	
	});
}

function updatePrice() {
    var shipping = $('#destination').val();
    
    if(shipping != undefined) {
        shipping = shipping.split('|');
        var cost = 0;
        var vatExempt = 0;
        var price = 0;
        
        $('.quantity').each(function() {
            if($(this).attr('data-vat') == 0) {
                vatExempt += (Number($(this).val()) * Number($(this).attr('data-price')));
            } else {
                cost += (Number($(this).val()) * Number($(this).attr('data-price')));
            }
        });
        
        if(cost > 0 || vatExempt > 0) {
            if((shipping[0] == 'europe' && $('#vat').val().length >= 9) || shipping[0] == 'restworld') {
                price = cost + vatExempt + Number(shipping[1]);
            } else {   
                price = (cost * 1.2) + vatExempt + Number(shipping[1]);
            }
        }
        
        if(shipping[0] == 'europe' && cost > 0) {
            $('#vat-container').show();
        } else {
            $('#vat-container').hide();
            $('#vat').val('');
        }
        
        $('#price').html(price.toFixed(2));
    }
}
