function Pagination(itemsPerPage, totalItems) {
    this.itemsPerPage = itemsPerPage;
    this.totalItems = totalItems;
    this.getPageCount = function() {
        return Math.ceil(this.totalItems / this.itemsPerPage);
    }
}

$(function() {

    var _selectedTag;
    var _selectedProductLine;
    var _page;
    var _itemsPerPage = 18;
    var _showDiscontinued = false;
    var _showOutOfStock = false;
    var _frontPageItemIndex = 0;

    if ($.browser.msie && $.browser.version < 8) {
        alert("Sorry, Pijin is only compatible with Internet Explorer version 8 or later.");
    }

    $('.next').click(function() {
        selectTag(_selectedTag, _page + 1);
    });

    $('.previous').click(function() {
        selectTag(_selectedTag, _page - 1, "right");
    });

    $.template("tagTemplate", $('#tag-template'));
    $('#tag-template').remove();

	$.template("searchResultTemplate", $('#search-result-template'));
    $('#search-result-template').remove();
    
    $('#alert-dialog').dialog({modal:true,minWidth:370,title:'Email Alert',autoOpen: false,closeOnEscape:true});

	$('.email-alert').live('click', function() {
		$('#confirm-alert-button').button('disable');
		$('#alert-email-field').val('');
		$('#alert-dialog').dialog('open');
		$('#alert-confirmation').hide();
		$('#alert-data').show();
		var $productRow = $(this).closest('.product-row');
		var productId = $productRow.data('id');
		var productName = $productRow.data('name');
		$('#alert-dialog').data('id', productId);
		$('#alert-dialog').data('name', productName);
		$('#alert-dialog-product-name').html(productName);
	});
	
	$('#alert-email-field').keyup(function() {
		updateAlertButtonState();
	});
	
	$('#confirm-alert-button').button().click(function() {
		var email = $('#alert-email-field').val();
		var productId = $('#alert-dialog').data('id');
		$('#alert-data').hide();
		$('#alert-confirmation').show();
		setTimeout(function() {$('#alert-dialog').dialog('close')}, 2000);
		PijinService.addAlert(email, productId);
	});

	$('#toggle-weight').live('click', function() {
		var $this = $(this);
		var imperialString = "imperial";
		var metricString = "metric"
		if ($this.text() == imperialString) {
			$this.text(metricString);
			$('.product-weight').text(function() {
				return getMetricWeight($(this).closest('.product-row').data('weight'))
			});
		} else {
			$this.text(imperialString);
			$('.product-weight').text(function() {
				return getImperialWeight($(this).closest('.product-row').data('weight'))
			});
		}		
	});
    
    $('#search-field').keyup(function() {
    	var $searchField = $(this);
    	var search = $searchField.val();
    	if (search == "") {
    		$('.search-result-row').remove();
    		$('#search-loading-image').hide();
    	} else {
			$('#search-loading-image').show();
			PijinService.searchProductLines(search, _showOutOfStock, _showDiscontinued, function(productLines) {
				if (search == $searchField.val()) {
					$('.search-result-row').remove();
					$('#search-loading-image').hide();
					if (productLines.length > 0) {
						$('#no-search-results').hide();
						$('#search-result-table').show();
						$.tmpl("searchResultTemplate", productLines, {stripWhitespace:stripWhitespace}).appendTo('#search-result-table');
					} else {
						$('#search-result-table').hide();
						$('#no-search-results').show();
					}
				}
			});
    	} 
    });
    
    $.template("basketItemTemplate", $('#basket-item-template'));
    $('#basket-item-template').remove();
    
    $('.add-to-basket').live('click', function() {
    	var $productRow = $(this).closest('.product-row');
    	var productId = $productRow.data('id');
    	var productName = $productRow.data('name');
    	var $basket = $('#basket');
    	var basketId = $basket.data('id') == null ? 0 : $basket.data('id');
    	$('#empty-basket').hide();
    	$basket.fadeIn('slow');
    	_gaq.push(['_trackEvent', 'Page', 'addToBasket', productName]);
    	PijinService.addToBasket(basketId, productId, 1, function(basket) {
    		storeBasketId(basket.id);
    		populateBasket(basket.items);
            $('.basket-item-row:first td').css('background-color', '#0F0').animate({'background-color':'#333'}, 3000);
    	});
    });
    
    $('.delete-basket-item').live('click', function() {
    	var $row = $(this).closest('.basket-item-row');
    	var basketId = $('#basket').data('id');
    	var productId = $row.data('product-id');
    	$row.fadeOut('slow', function() {
    		$row.remove();
            PijinService.deleteBasketItem(basketId, productId, function(basket) {
        	    if (basket.items.length == 0) {
        	        showEmptyBasket();
        	    } else {
        	        populateBasket(basket.items);
        	    }
        	});
    	});
    });
    
    $.template("frontPageItemTemplate", $('#front-page-item-template'));
    $('#front-page-item-template').remove();
    
    $.template("productLineListTemplate", $('#product-line-item'));
    $('#product-line-item').remove();
    $('.product-line-summary').hide();

    $.template("galleryTemplate", $('#gallery-section'));
    $('#gallery').hide();

    $.template("productThumbnailTemplate", $('#product-thumbnail'));
    $('#product-thumbnail').remove();
    
    $.template('productTemplate', $('#product-data'));
    $('#product-data').remove();

	$('#checkout-button').click(function() {
	    if ($('.basket-item-row').length > 0) { 
		    $('#basket-block').mask('Preparing checkout...');
		    var basketId = $('#basket').data('id');
		    _gaq.push(['_trackEvent', 'Page', 'checkout']);
		    
		    var pageTracker = _gaq._getAsyncTracker();
		    setUrchinInputCode(pageTracker);
		    
		    PijinService.checkOut(basketId, $('#analyticsdata').val(), function(redirect) {
			    _gaq.push(['_trackEvent', 'Page', 'checkout-success']);
			    window.location = redirect;			    
		    });
		} else {
		    $('#empty-basket').css('color', 'red').animate({'color':'#FFF'}, 300)
		}
		return false;
	});

	$('#include-in-stock-only').attr('checked', 'checked').change(function() {
		var isChecked = $(this).is(':checked');
		if (isChecked) {
			_showOutOfStock = false;
			_showDiscontinued = false;	
			$('#search-field').keyup();
		}
		if (_selectedProductLine != null) {
			refreshProductsDisplayed();
		} else {
			selectTag(_selectedTag, 1);
		}
	});
	
	$('#include-out-of-stock').removeAttr('checked').change(function() {
		var isChecked = $(this).is(':checked');
		if (isChecked) {
			_showOutOfStock = true;
			_showDiscontinued = false;	
			$('#search-field').keyup();
		}
		if (_selectedProductLine != null) {
			refreshProductsDisplayed();
		} else {
			selectTag(_selectedTag, 1);
		}
	});
	
	$('#include-discontinued').removeAttr('checked').change(function() {
		var isChecked = $(this).is(':checked');
		if (isChecked) {
			_showOutOfStock = true;
			_showDiscontinued = true;	
			$('#search-field').keyup();
		}
		if (_selectedProductLine != null) {
			refreshProductsDisplayed();
		} else {
			selectTag(_selectedTag, 1);
		}
	});

    PijinService.findAllPublishedTags(function(data) {
        $.tmpl("tagTemplate", data, {stripWhitespace:stripWhitespace}).appendTo($('#tags'));
        $('#tags').fadeIn('slow');
        highlightSelectedTag(_selectedTag);
    });

    $.address.init(function() {
	    $('.history-link').address();
	}).change(function(event) {	    
	    var pathArray = event.path.split('/');
	    if (pathArray[1] == "product") {
	        _gaq.push(['_trackEvent', 'Page', 'Click', pathArray[3]]);
	        showProductLine(pathArray[2]);
	        return;
	    } 
	    var tag = putWhitespaceBack(pathArray[1]);
	    var page = pathArray[2];
	    if (tag != '') {
	    	_gaq.push(['_trackEvent', 'Page', 'Click', tag]);
	    	selectTag(tag, page);
	    } else {
	    	_gaq.push(['_trackEvent', 'Page', 'Click', 'Front Page']);
	    	showFrontPage();
	    }
    });  
    
    loadBasketFromCookie();
    $('#search-field').val('');

	function storeBasketId(id) {
		$.data($('#basket')[0], 'id', id);
		$.cookie("basket", id, {path:'/', expires:14});
	}

    function showFrontPage() {
    	$('.front-page-item').remove();
    	$('#front-page-items-list').contents().remove();
    	$('#product-line-list').hide();
    	$('#product-line-details').hide();
    	$('#front-page').hide();
    	PijinService.findFrontPageProductLines(function(data) {
            $.tmpl("productLineListTemplate", data, {stripWhitespace:stripWhitespace}).appendTo('#front-page-items-list');
            $.tmpl("frontPageItemTemplate", data, {stripWhitespace:stripWhitespace}).appendTo('#front-page-items');
            $('#front-page').fadeIn('slow');
            $('.front-page-item').filter(':first').show();
        });
        $.address.title("Pijin");
        
        var $twitterFeed = $('#twitter-feed');
        $twitterFeed.contents().remove();
        $twitterFeed.getTwitter({
		    userName: 'pijinbmx',
		    numTweets: 3,
		    loaderText: 'Loading tweets...',
		    slideIn: false,
		    showHeading: true,
		    headingText: 'Latest Tweets',
		    showProfileLink: true
	    });
	    
	    var $blogFeed = $('#blog-feed');
	    $blogFeed.contents().remove();
	    $blogFeed.rssfeed('http://blog.pijin.co.uk/feeds/posts/default', {
		    limit: 3,
		    header:false
	    });
    }
        
    function doesTagExist(tag) {
        var isMatch = false;
        $('.tag').each(function() {
            if ($(this).text() == tag) {
                isMatch = true;
            }
        });
        return isMatch;
    }
    
    function loadBasketFromCookie() {
    	var basketId = $.cookie("basket");
    	loadBasket(basketId);
    }
    
    function loadBasket(basketId) {
    	if (basketId == null) {
    	    basketId = "";
    	}
		PijinService.getBasket(basketId, function(basket) {
			if (basket.id == null) {
				showEmptyBasket();
			} else {
				if (basket.items.length == 0) {
					showEmptyBasket();
				} else {
				    populateBasket(basket.items);
					$('#empty-basket').hide();
				}
				storeBasketId(basket.id);
			}
			$('#basket-block').fadeIn('slow');
		});
    }
    
    function populateBasket(basketItems) {
        $('.basket-item-row').remove();
        for (var i = 0; i < basketItems.length; i++) {
	        $.tmpl("basketItemTemplate", basketItems[i], {getFormattedPrice:getFormattedPrice}).prependTo($('#basket'));
	    }
	    updateBasketPrice();
    }
    
    function showEmptyBasket() {
    	$('#empty-basket').show();
   		$('#basket').hide();
   		$('.basket-item-row').remove();
   		updateBasketPrice();
   		$.data($('#basket')[0], 'id', '0');
   		$.cookie("basket", "0", {path:'/', expires:14});
    }
    
    function stripWhitespace(string) {     
        var strippedString = string.replace(/ /g, '_');
        return strippedString.replace(/[^*_A-z0-9\\-]/g, '');
    }
    
    function putWhitespaceBack(string) {     
        return string.replace(/_/g, ' ');
    }
    
    function getImperialWeight(grams) {
		if (grams == "0") {
			return "-"
		}
		var g = parseInt(grams);
		var p = g * 0.00220462262;
		var s = new String(p); 
		var dotIndex = s.indexOf('.')
		if (dotIndex > 0) {
			var decimalPlaces = s.length - dotIndex - 1;
			s = s.substring(0, s.length - (decimalPlaces - 2));
		}
		return s + " lbs";
	};
	
	function getMetricWeight(grams) {
		if (grams == "0") {
			return "-"
		}
		var g = parseInt(grams);
		if (g > 1000) {
			var kg = g / 1000;
			return new String(kg) + " kg";
		}
		if (g > 10000) {
			var kg = g / 1000;
			var s = new String(kg); 
			var dotIndex = s.indexOf('.')
			if (dotIndex > 0) {
				var decimalPlaces = s.length - dotIndex - 1;
				s = s.substring(0, s.length - (decimalPlaces - 2));
			}
			return s + " kg";
		}
		return grams + " g";
	};
    
    function showPagination(page, pagination) {
        $paginationControls = $('.pagination-controls');
        if (pagination.getPageCount() > 1) {
            $paginationControls.show();

            var $previous = $('.previous');
            if (page > 1) {
                $previous.show();
                $previous.attr('href', '#!/' + _selectedTag + '/' + (parseInt(page) - 1));
            } else { 
                $previous.hide();
            }

            var $next = $('.next');
            if (page < pagination.getPageCount()) {
                $next.show();
                $next.attr('href', '#!/' + _selectedTag + '/' + (parseInt(page) + 1));
            } else {
                $next.hide();
            }

            $('.current-page').text(page);
            $('.total-pages').text(pagination.getPageCount());

            var $pageLinks = $('.page-links');
            $pageLinks.empty();
            for (var i = 0; i < pagination.getPageCount(); i++) {
                var $link = $('<a class="page-link history-link"></a>');
                var linkPage = i + 1;
                (_page == linkPage) ? $link.addClass('page-link-selected') : $link.addClass('page-link');
                $link.text(linkPage).attr('href', '#!/' + _selectedTag + '/' + linkPage).appendTo($pageLinks);
            }

        } else {
            $paginationControls.hide();
        }
    }
    
    function highlightSelectedTag(tag) {
        $('.tag').each(function() {
            var $this = $(this);
            $this.toggleClass('tag-selected', $this.text() == tag);
        });  
    }

    function selectTag(tag, page) {
        if (tag == null) {
            showFrontPage();
            return;
        }
        if (page == null) {
            _page = 1;
            $('.product-line-summary').remove();
            $('#product-line-list').hide();
        } else {
            _page = page;
        }
        _selectedTag = tag;
        _selectedProductLine = null;
        
        highlightSelectedTag(tag);
        
        $('#product-line-details').hide();
        $('#no-product-line-found').hide();
        $('#front-page').hide();
        
        var metaDescription = tag + ":";
        $('link[rel=canonical]').attr('href', 'http://www.pijin.co.uk/#!/' + stripWhitespace(tag));
        
        PijinService.findAllPublished(_showDiscontinued, _showOutOfStock, _selectedTag, _page, _itemsPerPage, function(data) {
            if (data.totalResultCount > 0) {
            	$('.product-line-summary').remove();
                showPagination(_page, new Pagination(_itemsPerPage, data.totalResultCount));
                
                $('#product-line-items').hide();
                var $productLineItems = $('#product-line-items');
                $.tmpl("productLineListTemplate", data.results, {stripWhitespace:stripWhitespace}).appendTo($productLineItems);
                
                $('#product-line-list').fadeIn('slow');
                $('#product-line-items').fadeIn('slow');
                setTitle(_selectedTag + (parseInt(_page) > 1 ? ' - page ' + _page : ''));
                
                for (var i = 0; i < data.results.length; i++) {
                    metaDescription += data.results[i].description + ",";
                }
                $('meta[name=Description]').attr('content', metaDescription);
                
            } else {
                //showFrontPage();
            }
        });
    }
    
    function setTitle(title) {
        $.address.title("Pijin - " + title);
    }
    
    function isDisplayable(product) {
    	var displayable = true;
    	if (!_showOutOfStock && product.outOfStock) {
    		displayable = false;
    	}
    	if (!_showDiscontinued && product.discontinued) {
    		displayable = false;
    	} 
		return displayable;    	
    }

    function showProductLine(productLineId) {
    	_selectedTag = '';
        $('#product-line-name').text("");
        $('#product-line-description').html("");
        $('.fb-like').remove();
        $('.product-plusone').remove();
        
        $('#product-line-list').hide();
        $('#front-page').hide();
        
        $('#gallery-section').contents().remove();
        
        PijinService.findProductLineDetails(productLineId, function(data) {
            _selectedProductLine = data;
            if (data != null) {
            
                var url = 'http://www.pijin.co.uk/#!/product/' + productLineId + '/' + stripWhitespace(data.name);
                
                $('meta[property=og:title]').attr('content', data.name);
                $('meta[property=og:type]').attr('content', 'product');
                $('meta[property=og:url]').attr('content', url);
                $('meta[property=og:image]').attr('content', 'http://www.pijin.co.uk/images/' + data.images[0].filename);
            
            	$('#no-product-line-found').hide();
		        $('#product-line-details').fadeIn('slow');
		        $('#product-line-name').text(data.name);
		        setTitle(data.name);
		        if (data.shortDescription == null) {
		            $('meta[name=Description]').attr('content', data.name);
		        } else {
		            $('meta[name=Description]').attr('content', data.shortDescription);
		            $('meta[property=og:description]').attr('content', data.shortDescription);
		        }
		        $('link[rel=canonical]').attr('href', url);
		        if (data.images.length > 1) {
			        $('#gallery-section').show();
		            $.tmpl("galleryTemplate").appendTo($('#gallery-section'));
		            $('#gallery').fadeIn('slow');
		            $.tmpl("productThumbnailTemplate", data.images).appendTo($('.ad-thumb-list'));
		            $('.ad-gallery').adGallery();
		        } else if (data.images.length == 1) {
		        	$('#gallery-section').show();
		            $('<img class="product-image">').attr('src', "images/" + data.images[0].filename).appendTo($('#gallery-section'));
		        } else {
		        	$('#gallery-section').hide();
		        }
		        $('#product-line-description').html(data.description);
		        $('#product-line-footer').html(data.footer);
		        $('#product-social-section').append($('<div class="fb-like" data-send="true" data-width="550" data-show-faces="true" data-colorscheme="dark"></div>'));
		        FB.XFBML.parse();
		        $('#product-social-section').append($('<div class="product-plusone"><g:plusone href="' + url + '"></g:plusone></div>'));
		        gapi.plusone.go();
		        
		        refreshProductsDisplayed();
		    } else {
			    $('#product-line-details').hide();
		    	$('#no-product-line-found').fadeIn('slow');
		    }
        });
    }
    
    function refreshProductsDisplayed() {
        $('.product-row').remove();
        var products = _selectedProductLine.products;
        for (var i = 0; i < products.length; i++) {
        	var product = products[i];
        	if (isDisplayable(product)) {
		        $.tmpl("productTemplate", product, {
		        	getFormattedPrice:getFormattedPrice,
		        	getMetricWeight:getMetricWeight,
		        	getImperialWeight:getImperialWeight
		        }).appendTo($('#products'));
            }
        }
        var showWeight = false;
        for (i = 0; i < products.length; i++) {
        	if (products[i].weightInGrams != "0") {
        		showWeight = true;
        		break;
        	}
        }
        $('#toggle-weight').text("metric");
        if (showWeight) {
        	$('.product-weight-header').show();
        	$('.product-weight').show();
        } else {
        	$('.product-weight-header').hide();
        	$('.product-weight').hide();
        }
        var showDiscount = false;
        for (i = 0; i < products.length; i++) {
        	if (products[i].rrp - products[i].price > 0) {
        		showDiscount = true;
        		break;
        	}
        }
        if (showDiscount) {
        	$('.product-discount-header').show();
        	$('.product-discount').show();
        } else {
        	$('.product-discount-header').hide();
        	$('.product-discount').hide();
        }
        if ($('.product-row').length > 0) {
        	$('#out-of-stock').hide();
			$('#products').show();
        } else {
   			$('#products').hide();
        	$('#out-of-stock').show();
        }
    }
	
	function getFormattedPrice(pennies, includePoundSign) {
		var s = new String(parseInt(pennies) / 100);
		if (s.indexOf('.') < 0) {
			s += ".00";
		}
		while (s.indexOf('.') > s.length - 3) {
			s += "0";
		}
		return includePoundSign ? "&pound;" + s : s;
	};
	
	function updateBasketPrice() {
		var pennies = 0;
		$('.basket-item-row').each(function() {
			var $this = $(this);
			pennies += (parseInt($this.data('price')) * parseInt($this.data('quantity')));
		});
		$('#basket-price').html(getFormattedPrice(pennies, true));
	}

	function updateAlertButtonState() {
    	if ($('#alert-email-field').val().trim().match("^[A-z0-9._%-]+@[A-z0-9.-]+\\.[A-z]{2,4}$")) {
    		$('#alert-email-field').removeClass("error");
    		$('#confirm-alert-button').button('enable');
    	} else {
	    	$('#alert-email-field').addClass("error");
    		$('#confirm-alert-button').button('disable');
    	}
    }
    
    function scrollToNextFrontPageItem() {
		var count = $('.front-page-item').length;
		$($('.front-page-item').get(_frontPageItemIndex)).hide('slide', {direction:'left'}, 1000);
		if (_frontPageItemIndex < count - 1) {
		    _frontPageItemIndex++;
		} else {
		    _frontPageItemIndex = 0;
		}
		$($('.front-page-item').get(_frontPageItemIndex)).show('slide', {direction:'right'}, 1000);
	}
	
	setInterval(function() {scrollToNextFrontPageItem()}, 6000);
});

