var productionMode = true;
var appLoaded = false;

function imagePath() {
	if (productionMode) {
		return '/images/store/';
	} else {
		return 'images/store/';
	}
}

function url(test, production) {
	if (productionMode) {
		return applicationURL + '/wa/' + production;
	} else {
		return test;
	}
}



var AppRouter = Backbone.Router.extend({
	initialize: function(controller) {
		var self = this;

		this.controller = controller;
				
		this.currentWindow = null;
		//this.categoryOptionDropdownIsOpen = false;
		this.savedState = null;
	},
	
	routes: {
		"!/state/:state": "loadCollectionContent",
		"!/state/:state/details/:itemid": "loadDetails",
		//"!/details/:state": "loadDetails",
		"!/details/:itemid": "loadDetails2",
		"!/search=:query": "loadSearch",
		"*actions": "defaultRoute"
	},
	
	loadCollectionContent: function(state) {
		var self = this;
		
		this.controller.detailsView.close();
		if (this.savedState != state) {
			if ((state == '') || (state == 'x')) {
				if (appLoaded) {
					this.controller.collectionView.loadContent(url('content-ajax-2.html', 'collection'), 'param=' + state + '&wosid=' + wosid);
				}
			} else {
				this.controller.collectionView.loadContent(url('content-ajax-2.html', 'collection'), 'param=' + state + '&wosid=' + wosid);
			}
			this.controller.sidebarView.setSelection(state);
		}
			
		this.savedState = state;
	},
	
	loadDetails: function(state, itemid) {
		/*
		var self = this;
		self.detailsView.open(itemid, state);
		*/
		
		if (this.getCurrentWindow() != null) {
			this.getCurrentWindow().close();
		}
		
		//var model = this.itemCollection.get(itemid);
		this.controller.curtain.open(true);
		this.controller.detailsView.open(itemid, state);
		//this.setCurrentWindow(this.detailsView);
	},
	
	loadDetails2: function(itemid) {
		this.loadDetails('#', itemid);
	},
	
	loadSearch: function(query) {
		var self = this;
		//alert('query: ' + query);
		
		this.controller.detailsView.close();
		if (this.savedState != 'search/' + query) {
			this.controller.collectionView.loadContent(url('content-ajax-2.html', 'entirecollection'), 'search=' + query + '&wosid=' + wosid);
			this.controller.sidebarView.setSelection('search');
		}
		this.savedState = 'search/' + query;
	},
	
	defaultRoute: function() {
		var self = this;
		
		if (appLoaded) {
			this.controller.detailsView.close();
			if (this.savedState != 'default') {
				this.controller.collectionView.loadContent(url('', 'collection'), 'wosid=' + wosid);
				this.controller.sidebarView.setSelection('default');
			}
		}
		
		this.savedState = 'default';
	},
	
	setCurrentWindow: function(object) {
		this.currentWindow = object;
	},
	
	getCurrentWindow: function() {
		return this.currentWindow;
	},
});


var RootController = Backbone.Router.extend({
	initialize: function() {
		this.viewController;
	},
	
	initializeHomeController: function() {
		this.viewController = new HomeViewController();
	},
	
	initializeEntireCollectionState: function() {
		this.viewController = new EntireCollectionViewController();
	},
	
	initializeContactState: function() {
		this.viewController = new ContactViewController();
	},
	
	initializeCheckoutState: function() {
		this.viewController = new CheckoutViewController();
	}
});

var HomeViewController = Backbone.Router.extend({
	initialize: function() {
		var self = this;
		
		this.appRouter = new AppRouter(this);
		
		this.mainView = new MainView();
		this.headerView = new HeaderView();
		this.curtain = new Curtain();
		this.subscribe = new Subscribe();
		this.detailsView = new DetailsView(this);
				
		this.storeItem = new StoreItem();
		this.collectionItemView = new CollectionItemView(this.storeItem);
		this.detailsItemView = new DetailsItemView(this.storeItem);
		
		this.favorites = new Favorites(this, this.storeItem);
		this.shoppingCart = new ShoppingCart(this, this.storeItem);
		
		this.mainImage = new MainImage();
	
		Backbone.history.start();
	
		this.resize();
		$(window).resize(function() {
			self.resize();
		});
	},
	
	resize: function() {
		this.mainView.resize();
		
		this.curtain.resize();
		
		this.detailsView.resize();
		
		this.mainImage.resize();
	}
});


var ContactViewController = Backbone.Router.extend({
	initialize: function() {
		var self = this;
		
		this.appRouter = new AppRouter(this);
		
		this.mainView = new MainView();
		this.headerView = new HeaderView();
		this.curtain = new Curtain();
		this.subscribe = new Subscribe();
		this.detailsView = new DetailsView(this);
				
		this.storeItem = new StoreItem();
		this.collectionItemView = new CollectionItemView(this.storeItem);
		this.detailsItemView = new DetailsItemView(this.storeItem);
		
		this.favorites = new Favorites(this, this.storeItem);
		this.shoppingCart = new ShoppingCart(this, this.storeItem);
		
		this.contactView = new ContactView();
	
		Backbone.history.start();
	
		this.resize();
		$(window).resize(function() {
			self.resize();
		});
	},
	
	resize: function() {
		this.mainView.resize();
		
		this.curtain.resize();
		
		this.detailsView.resize();
		
		this.contactView.resize();
	}
});

var CheckoutViewController = Backbone.Router.extend({
	initialize: function() {
		var self = this;
		
		this.mainView = new MainView();
	
		this.checkoutView = new CheckoutView();
	
		this.resize();
		$(window).resize(function() {
			self.resize();
		});
	},
	
	resize: function() {
		this.mainView.resize();
		
		this.checkoutView.resize();
	}
});



var EntireCollectionViewController = Backbone.Router.extend({
	initialize: function() {
		var self = this;
		
		this.appRouter = new AppRouter(this);
		
		this.mainView = new MainView();
		this.headerView = new HeaderView();
		this.curtain = new Curtain();
		this.subscribe = new Subscribe();
		this.detailsView = new DetailsView(this);
	
		this.storeItem = new StoreItem();
		this.collectionItemView = new CollectionItemView(this.storeItem);
		this.detailsItemView = new DetailsItemView(this.storeItem);
		this.search = new Search();
		
		this.collectionView = new CollectionView(this.storeItem);
		
		this.favorites = new Favorites(this, this.storeItem);
		this.shoppingCart = new ShoppingCart(this, this.storeItem);
		
		
		this.sidebarView = new SidebarView();
		
		Backbone.history.start();
		
		appLoaded = true;
	
		this.resize();
		$(window).resize(function() {
			self.resize();
		});
	},
	
	resize: function() {
		this.mainView.resize();
		
		this.curtain.resize();
		
		this.sidebarView.resize();
		
		this.collectionView.sizeContent();
		this.collectionView.render();
		
		this.detailsView.resize();
	}
});


var StoreItem = Backbone.Model.extend({
	initialize: function() {
		var self = this;
		
		this.id;
	},
	
	addToFavorites: function(id) {
		//alert('adding to shopping cart');
		this.id = id;
		this.trigger('change:addToFavorites');
	},
	
	removeFromFavorites: function(id) {
		this.id = id;
		this.trigger('change:removeFromFavorites');
	},
	
	addToShoppingCart: function(id) {
		//alert('adding to shopping cart');
		//this.set({ "inShoppingCart": 1 });
		this.id = id;
		this.trigger('change:addToShoppingCart');
	},
	
	removeFromShoppingCart: function(id) {
		this.id = id;
		this.trigger('change:removeFromShoppingCart');
	}
});


var CollectionItemView = Backbone.View.extend({
	initialize: function(model) {
		this.model = model;
		
		this.model.bind('change:addToFavorites', this.addToFavorites, this);
		this.model.bind('change:removeFromFavorites', this.removeFromFavorites, this);
		
		this.model.bind('change:addToShoppingCart', this.addToShoppingCart, this);
		this.model.bind('change:removeFromShoppingCart', this.removeFromShoppingCart, this);
		
		this.preloadImages();
	},
	
	addToFavorites: function() {
		var id = this.model.id;
		
		$('#item' + id + ' .buttonFavorite').hide();
		$('#item' + id + ' .buttonFavoriteSelected').show();
	},
	
	removeFromFavorites: function() {
		var id = this.model.id;
		
		if ($('#item' + id).length > 0) {
			$('#item' + id + ' .buttonFavorite').show();
			$('#item' + id + ' .buttonFavoriteSelected').hide();
		}
	},
	
	addToShoppingCart: function() {
		var id = this.model.id;
		//alert('collection item - shopping cart - add id:' + id);
		
		$('#item' + id + ' .buttonBuy').hide();
		$('#item' + id + ' .labelInShoppingCart').show();
	},
	
	removeFromShoppingCart: function() {
		var id = this.model.id;
		//alert('collection item - shopping cart - remove id:' + id);
		
		if ($('#item' + id).length > 0) {
			$('#item' + id + ' .buttonBuy').show();
			$('#item' + id + ' .labelInShoppingCart').hide();
		}
	},
	
	preloadImages: function() {
		var buttonFavoriteMO = new Image(28, 25);
		buttonFavoriteMO.src = imagePath() + 'button-favorite-mo.jpg';
		
		var buttonFavoriteMC = new Image(28, 25);
		buttonFavoriteMC.src = imagePath() + 'button-favorite-mc.jpg';
		
		var buttonFavoriteSelected = new Image(28, 25);
		buttonFavoriteSelected.src = imagePath() + 'button-favorite-selected.jpg';
	}
});


var DetailsItemView = Backbone.View.extend({
	initialize: function(model) {
		this.model = model;
		
		this.model.bind('change:addToFavorites', this.addToFavorites, this);
		this.model.bind('change:removeFromFavorites', this.removeFromFavorites, this);
		
		this.model.bind('change:addToShoppingCart', this.addToShoppingCart, this);
		this.model.bind('change:removeFromShoppingCart', this.removeFromShoppingCart, this);
		
		this.preloadImages();
	},
	
	addToFavorites: function() {
		var id = this.model.id;
		
		$('#buttonDetailsFavorites').hide();
		$('#buttonDetailsFavoritesSelected').show();
	},
	
	removeFromFavorites: function() {
		var id = this.model.id;
		
		$('#buttonDetailsFavorites').show();
		$('#buttonDetailsFavoritesSelected').hide();
	},
	
	addToShoppingCart: function() {
		var id = this.model.id;
		//alert('collection item - shopping cart - add id:' + id);
		
		$('#buttonDetailsBuy').hide();
		$('#buttonDetailsBuySelected').show();
	},
	
	removeFromShoppingCart: function() {
		var id = this.model.id;
		//alert('collection item - shopping cart - remove id:' + id);
		
		$('#buttonDetailsBuy').show();
		$('#buttonDetailsBuySelected').hide();
	},
	
	preloadImages: function() {
		/*
		var buttonFavoriteMO = new Image(28, 25);
		buttonFavoriteMO.src = imagePath() + 'button-favorite-mo.jpg';
		
		var buttonFavoriteMC = new Image(28, 25);
		buttonFavoriteMC.src = imagePath() + 'button-favorite-mc.jpg';
		
		var buttonFavoriteSelected = new Image(28, 25);
		buttonFavoriteSelected.src = imagePath() + 'button-favorite-selected.jpg';
		*/
	}
});


var HeaderButton = Backbone.View.extend({
	initializeSuper: function(view, filename) {
		this.view = view;
		this.filename = filename;
		//alert(this.filename);
		
		this.bindHoverEffects();
	},
	
	bindHoverEffects: function() {
		var self = this;
		this.view.mouseover(function () {
			$(this).css({ backgroundImage: 'url(' + imagePath() + 'button-' + self.filename + '-mo.jpg)' });
		});
		
		this.view.mouseout(function () {
			$(this).css({ backgroundImage: 'url(' + imagePath() + 'button-' + self.filename + '.jpg)' });
		});
	},
	
	unbindHoverEffects: function() {
		this.view.unbind('mouseover').unbind('mouseout');
	},
	
	defaultState: function() {
		this.view.css({ backgroundImage: 'url(' + imagePath() + 'button-' + this.filename + '.jpg)' });
		
		this.bindHoverEffects();
	},
	
	pressedState: function() {
		this.view.css({ backgroundImage: 'url(' + imagePath() + 'button-' + this.filename + '-mc.jpg)' });
		
		this.unbindHoverEffects();
	}
});

var ShoppingCartButton = HeaderButton.extend({
	initialize: function() {
		this.view = $('#buttonShoppingCart');
		this.initializeSuper(this.view, 'shoppingcart');
		
		this.preloadImages();
	},
	
	preloadImages: function() {
		var buttonShoppingCartMO = new Image(34, 30);
		buttonShoppingCartMO.src = imagePath() + 'button-shoppingcart-mo.jpg';
		
		var buttonShoppingCartMC = new Image(34, 30);
		buttonShoppingCartMC.src = imagePath() + 'button-shoppingcart-mc.jpg';
	}
});

var FavoritesButton = HeaderButton.extend({
	initialize: function() {
		this.view = $('#buttonFavorites');
		this.initializeSuper(this.view, 'favorites');
		
		this.preloadImages();
	},
	
	preloadImages: function() {
		var buttonFavoritesMO = new Image(34, 30);
		buttonFavoritesMO.src = imagePath() + 'button-favorites-mo.jpg';
		
		var buttonFavoritesMC = new Image(34, 30);
		buttonFavoritesMC.src = imagePath() + 'button-favorites-mc.jpg';
	}
});



var HeaderView = Backbone.View.extend({
	//el: '.header',
	
	initialize: function() {			
		var self = this;
		self.x = false;
		
		self.setDefaults();
		self.linkEffects();
	
		self.resize();
		$(window).resize(function() {
			self.resize();
		});
	},
	
	resize: function() {
		var self = this;
		
		if ($(window).width() < 1000) {
			if (!self.x) {
				$('#subscribeField').animate({ width: 95 });
				$('.navigationLinks a').animate({ paddingLeft:'6px', paddingRight:'6px' });
				self.x = true;
			}
		} else {
			if (self.x) {
				//$('#subscribeField').width(self.subscribeWidth);	
				$('#subscribeField').animate({ width: self.subscribeWidth });
				$('.navigationLinks a').animate({ paddingLeft:'10px', paddingRight:'10px' });
				self.x = false;
			}
		}
	},
	
	linkEffects: function() {
		$('.navigationLinks a').each(function() {
			if ($(this).attr('class') != 'selected') {
				$(this).hover(
					function () {
						$(this).animate({ color: '#fff' }, 200);
					},
					function () {
						$(this).animate({ color: '#B8B8B8' }, 200);
					}
				);
			}
		});
	},
	
	setDefaults: function() {
		var self = this;
		
		self.subscribeWidth = $('#subscribeField').width();
	}
});

var MainView = Backbone.View.extend({
	el: '#main',
	
	initialize: function() {
	},
	
	resize: function() {
		$('#main').height($(window).height() - $('#main').offset().top);
	}
});

var DetailsView = Backbone.View.extend({
	el: '#details',
	
	initialize: function(controller) {		
		this.controller = controller;
	
		this.isOpen = false;
		this.closePressed = false;
		this.loadingDetails = false;
		
		/*
		this.resize();
		$(window).bind('resize', this.resize);*/
	},
	
	resize: function() {
		$('#details').css({ height: ($(window).height() - $('#details').offset().top) + 'px' });
	},
	
	open: function(itemID, state) {
		if (this.isOpen) {
			//this.close();	
		}
		
		var self = this;
		self.closePressed = false;
		self.loadingDetails = true;
		
		this.controller.curtain.close();
		
		self.loadDetails = $.ajax({
			url: url('details-ajax.html', 'item'),
			data: 'itemID=' + itemID + '&wosid=' + wosid,
			error: function() {
				alert('error');
			},
			success: function(response) {
				//alert(self.closePressed);
				if (!self.closePressed) {
					$('#details').show();
					$('#details').html(response);
					$('#buttonDetailsBack').attr('href', '#!/state/' + state);
					self.controller.curtain.close();
					
					self.loadingDetails = false;
					//self.isOpen = true;
				}
			}
		});
		
		this.isOpen = true;
	},
	
	addObjects: function(infoPanelView, imageViewer) {
		this.infoPanelView = infoPanelView;
		this.imageViewer = imageViewer;
	},
	
	close: function() {
		//this.isOpen = false;
		this.closePressed = true;
		
		if (this.loadingDetails) {
			this.curtain.close();
			this.loadDetails.abort();
		}
		
		$('#details').hide();
		$('#details').empty();
		
		if (this.infoPanelView != null) {
			this.infoPanelView.unbindEvents();
			delete this.infoPanelView;
		}
		
		if (this.imageViewer != null) {
			this.imageViewer.unbindEvents();
			delete this.imageViewer;
		}
		
		this.isOpen = false;
	}
});


var Curtain = Backbone.View.extend({
	el: '#curtain',
	
	initialize: function(appView) {		
		this.isOpen = false;
		this.spinner = false;
		
		this.appView = appView;
	},
	
	resize: function() {
		$('#curtain').css({ height: ($(window).height() - 70) + 'px' });
		
		$('#curtainSpinner').css({ 
			left: ($('#curtain').width() - $('#curtainSpinner').width()) / 2,
			top: ($('#curtain').height() - $('#curtainSpinner').height()) / 2
		});
	},
	
	open: function(spinner) {
		if (spinner != null) {
			this.spinner = true;
		}
		
		
		if (this.spinner) {
			$('#curtainSpinner').show();
		}
		
		$('#curtain').show();
		//alert('test');
	},
	
	close: function() {
		if (this.spinner) {
			$('#curtainSpinner').hide();
			this.spinner = false;
		}
		
		$('#curtain').hide();
	}
});


var Subscribe = Backbone.View.extend({
	el: '#subscribe',
	
	initialize: function() {
		this.field = $('#subscribeField');
		
		this.preloadImages();
	},
	
	events: {
		'click #buttonSubscribe': 'subscribe',
		'focus #subscribeField': 'focus',
		'blur #subscribeField': 'blur',
		'keyup #subscribeField': 'keyPressHandler'
	},
	
	subscribe: function() {
		var self = this;
		
		var email = self.field.val();
		
		if (validateEmail(email)) {
			$.ajax({
				url: url('content-ajax-2.html', 'subscribe'),
				data: 'email=' + email + '&wosid=' + wosid,
				error: function() {
					$('#subscribeMessage').attr('class', 'subscribeMessageError');
					$('#subscribeMessage span').html('Error: Something is wrong with server');
					$('#subscribeMessage').show('slide', { direction: 'right' }, 200);
					$(self.field).blur();
					setTimeout(function() {
						$('#subscribeMessage').hide('slide', { direction: 'right' }, 200);
					}, 5000);
				},
				success: function(response) {
					$('#subscribeMessage').attr('class', 'subscribeMessageSuccess');
					$('#subscribeMessage span').html('Thank you for subscribing!');
					$('#subscribeMessage').show('slide', { direction: 'right' }, 200);
					$(self.field).blur();
					setTimeout(function() {
						$(self.field).val('subscribe email');
						$(self.field).css({ color: '#B1B1B1' });
						//$(self.field).blur();
						$('#subscribeMessage').hide('slide', { direction: 'right' }, 200);
					}, 5000);
				}
			});
		} else {
			$('#subscribeMessage').attr('class', 'subscribeMessageError');
			$('#subscribeMessage span').html('Error: Incorrect email address');
			$('#subscribeMessage').show('slide', { direction: 'right' }, 200);
			$(self.field).blur();
			setTimeout(function() {
				$('#subscribeMessage').hide('slide', { direction: 'right' }, 200);
			}, 5000);
		}
	},
	
	focus: function() {
		if($(this.field).val() == 'subscribe email') {
			$(this.field).val('');
			$(this.field).css({ color: '#E9E9E9' });
		}
	},
	
	blur: function() {
		if($(this.field).val() == '') {
			$(this.field).val('subscribe email');
			$(this.field).css({ color: '#B1B1B1' });
		}
	},
	
	keyPressHandler: function(event) {
		if (event.keyCode == 13) {
			this.subscribe();
		}
	},
	
	preloadImages: function() {
		var buttonSubscribeMO = new Image(33, 26);
		buttonSubscribeMO.src = imagePath() + 'button-subscribe-mo.jpg';
		
		var buttonSubscribeMC = new Image(33, 26);
		buttonSubscribeMC.src = imagePath() + 'button-subscribe-mc.jpg';
	}
});



var SidebarView = Backbone.View.extend({
	el: '#sidebar',
	
	initialize: function() {
		this.resize();
		$(window).bind('resize', this.resize);
	},
	
	setSelection: function(state) {
		$('#sidebar a').each(function() {
		
			if ($(this).attr('class') == 'selected') {
				$(this).removeClass('selected');
			}
			
			if (state == 'default') {
				if ('#' == $(this).attr('href')) {
					$(this).attr('class', 'selected');
				}
			} else if ('#!/state/' + state == $(this).attr('href')) {
				$(this).attr('class', 'selected');
			}
		});
	},
	
	scrollToggle: function() {		
		if (($.browser.msie) && (($.browser.version == "6.0") || ($.browser.version == "7.0"))) {
		} else {
			$('#sidebar').mouseover(function(){ 
				//alert('on');
				$('#sidebar .categories').css({ overflow:'auto' });
			});
			
			$('#sidebar').mouseout(function(){ 
				//alert('out');
				$('#sidebar .categories').css({ overflow:'hidden' });
			});	
		}
	},
	
	resize: function() {
		$('#sidebar').css({ height: ($(window).height() - $('#sidebar').offset().top) + 'px' });
		
		$('#sidebar .categories').each(function(value, element) {
			$(element).css({ height: ($(window).height() - $(element).offset().top) + 'px' });
		});
	}
});

var Search = Backbone.View.extend({
	el: '#search',
	
	initialize: function() {
		this.field = $('#searchField');
	},
	
	events: {
		'click #buttonSearch': 'search',
		'focus #searchField': 'focus',
		'blur #searchField': 'blur',
		'keyup #searchField': 'keyPressHandler'
	},
	
	search: function() {
		var self = this;
		window.location = '#!/search=' + self.field.val();
	},
	
	focus: function() {
		if($(this.field).val() == 'search') {
			$(this.field).val('');
			$(this.field).css({ color: '#333' });
		}
	},
	
	blur: function() {
		if($(this.field).val() == '') {
			$(this.field).val('search');
			$(this.field).css({ color: '#676767' });
		}
	},
	
	keyPressHandler: function(event) {
		if (event.keyCode == 13) {
			this.search();
		}
	}
});

var CollectionView = Backbone.View.extend({
	el: '#collectionContainer',
	
	initialize: function() {
		var self = this;
		
		this.cellWidth = $('.item').width();
		//this.minCellWidth = 380;
	},
	
	sizeContent: function() {
		$(this.el).css({ width: ($(window).width() - $(this.el).offset().left) + 'px' });
		$('#collectionView').css({ height: ($(window).height() - $('#collectionView').offset().top) + 'px' });
		
		$('#collectionSpinner').css({ 
			left: ($('#collectionView').width() - $('#collectionSpinner').width()) / 2,
			top: ($('#collectionView').height() - $('#collectionSpinner').height()) / 2
		});
	},
	
	render: function() {
		//alert('teeesst');
		var cellsInRow = 0;
		
		
		for (i = 1; i < 10; i++) {
			if (($('#collectionViewContent').width() < (this.cellWidth * (i + 1))) && ($('#collectionViewContent').width() > (this.cellWidth * i))) {
				cellsInRow = i;
			}
		}
		
		
		$('.item').each(function(i) {
			if ($('.item').length < cellsInRow) {
				$(this).css({ width: $('#collectionViewContent').width() / $('.item').length - 1 });
			} else {
				$(this).css({ width: $('#collectionViewContent').width() / cellsInRow - 1 });
			}
		});
		//alert(cellsInRow);
		
		var rowStart = 1;
		var rowEnd = cellsInRow;
		var heights = new Array();
		
		//alert($('.testItem').length);
		for (i = 1; i <= $('.item').length; i++) {
			//alert(i);
			if (i <= rowEnd) {
				var element = $('.item .itemImage')[i - 1];
				heights.push($(element).height());
				//alert(i + '   ' + rowEnd);
			}
			
			if ((i == rowEnd) || (i == $('.item').length)) {
				//alert(i + ' end');
				for (i2 = rowStart; i2 <= rowEnd; i2++) {
					//alert(rowStart + '    ' + rowEnd);
					var element = $('.item .imageContainer')[i2 - 1];
					$(element).height(Math.max.apply(Math, heights) + 30);
				}
				heights.length = 0;
				rowStart = i + 1;
				rowEnd = rowEnd + cellsInRow;
			}
		}
		
		$('.item .itemImage').each(function(i) {
			var imageContainer = $('.item .imageContainer')[i];
			
			$(this).css({ marginTop: ($(imageContainer).height() - $(this).height()) / 2 });
		});
	},
	
	loadContent: function(url, data) {
		var self = this;
				
		$('#collectionViewContent').html('');
		$('#collectionSpinner').show();
		
		$('.optionsBar .content').fadeOut();
		$.ajax({
			url: url,
			data: data,
			error: function() {
				alert('error');
			},
			success: function(response) {
				//alert(response);
				//$('.optionsBar .content').fadeIn();
				$('#collectionSpinner').hide();
				var itemsData = $(response).find('#collectionViewContent').html();
				var optionsBarData = $(response).find('.optionsBar').html();
				//alert($(response).find('.optionsBar').html());
				
				$('#collectionViewContent').html(itemsData);
				$('.optionsBar').html(optionsBarData);
				
				$('.optionsBar .content').fadeIn();
				
				self.render();
			}
		});
	}
});





var DropdownView = Backbone.View.extend({
	init: function(name, object) {
		var self = this;
		this.name = name;
	
		this.button = $('#button' + name.charAt(0).toUpperCase() + name.slice(1));
		this.window = $('#' + name + 'Window');
		this.object = object;
				
		this.isOpen = false;
		this.isEmpty = false;
		
		self.bindItemRowHover();
		
		self.checkIfEmpty();
						
		this.resize();
		$(window).resize(function() {
			self.resize();
		});
		
		this.preloadCloseButton();
	},
	
	bindItemRowHover: function() {
		$('.dropdownWindow tr').live('mouseenter', function() {
			$(this).css({ backgroundColor: '#EDEDED' });
			//$(this).children('td').children('.itemImage').css({ opacity: 0.7 });
			$(this).children('td').children('.buttonRemove').fadeIn(200);
		});
		
		$('.dropdownWindow tr').live('mouseleave', function() {
			$(this).css({ backgroundColor: '#F4F4F4' });
			//$(this).children('td').children('.itemImage').css({ opacity: 1 });
			$(this).children('td').children('.buttonRemove').fadeOut(200);
		});
	},
	
	checkIfEmpty: function() {		
		if ($(this.window).find('tr').length > 0) {
			this.isEmpty = false;
			this.resize();
		} else {
			this.isEmpty = true;
			$(this.window).find('.content').html('<p class="labelEmpty" style="text-align:center; margin-top:55px; font-size:30px; color:#ccc;">' + this.name + ' is empty</div>');
			$(this.window).find('.content').css({ height: 150 + 'px' });
		}
		
		return this.isEmpty;
	},
	
	setItemCount: function() {
		//alert('test');
		var itemCount = $(this.window).find('tr').length;
		//alert(itemCount);
		$(this.window).find('.itemCount').html(itemCount);
	},
	
	toggleState: function() {
		var self = this;
		
		if (self.isOpen) {
			self.close();	
		} else {
			self.open();	
		}
	},
	
	open: function() {
		var self = this;
		this.resize();
						
		this.window.fadeIn();
		
		self.isOpen = true;
	},
	
	close: function() {
		var self = this;

		this.window.fadeOut();
		
		self.isOpen = false;
	},
	
	resize: function() {
		if (!this.isEmpty) {
			$(this.window).find('.content').css({ height: ($(window).height() - 160) + 'px' });
		}
		
		$(this.window).css({ left: ($(this.button).offset().left - 400) + 'px' });
	},
	
	preloadCloseButton: function() {
		var buttonCloseMO = new Image(22, 24);
		buttonCloseMO.src = imagePath() + 'button-dropdown-close-mo.jpg';
		
		var buttonCloseMC = new Image(22, 24);
		buttonCloseMC.src = imagePath() + 'button-dropdown-close-mc.jpg';
	}
});


var FavoritesView = DropdownView.extend({	
	el: '#favoritesWindow',
	
	initialize: function(model) {
		var self = this;
		this.init('favorites', this);
		this.model = model;
		
		this.model.bind('change:addToFavorites', this.add, this);
		this.model.bind('change:removeFromFavorites', this.remove, this);
		
		this.preloadImages();
	},
	
	add: function(itemID) {
		var self = this;
		var id = this.model.id;
		
		$.ajax({
			url: url('search-results.php', 'addtofavorites'),
			data: 'itemID=' + id + '&wosid=' + wosid,
			error: function() {
				alert('error');
			},
			success: function(response) {
				$('#favoritesWindow .content').html(response);
				self.setItemCount();
				self.checkIfEmpty();
			}
		});
	},
	
	remove: function() {
		var self = this;
		var id = this.model.id;
		
		$('#favoritesItem' + id).fadeOut(500, function() { 
			$(this).remove(); self.setItemCount(); 
		});
		
		$.ajax({
			url: url('search-results.php', 'removefromfavorites'),
			data: 'itemID=' + id + '&wosid=' + wosid,
			error: function() {
				alert('error');
			},
			success: function(response) {
				var filteredResponse = jQuery.trim(response);
				if (filteredResponse == "true") {
					self.setItemCount();
					self.checkIfEmpty();
				} else {
					$('#favoritesWindow .content').html(response);
				}
			}
		});
		
	},
	
	preloadImages: function() {
		var buttonFavoritesMO = new Image(34, 30);
		buttonFavoritesMO.src = imagePath() + 'button-favorites-mo.jpg';
		
		var buttonFavoritesMC = new Image(34, 30);
		buttonFavoritesMC.src = imagePath() + 'button-favorites-mc.jpg';
	}
});


var ShoppingCart = Backbone.Router.extend({
	initialize: function(controller, model) {
		var self = this;
		this.isOpen = false;
		this.controller = controller;
		
		this.windowView = new ShoppingCartView(model);
		this.button = new ShoppingCartButton();
		
		this.button.view.click(function() { 
			self.toggleState();
		});
	},
	
	toggleState: function() {
		var self = this;
		
		if (this.isOpen) {
			this.close();	
		} else {
			this.open();
		}
	},
	
	open: function() {
		if (this.controller.appRouter.getCurrentWindow() != null) {
			this.controller.appRouter.getCurrentWindow().close();
		}
		
		this.windowView.open();
		this.controller.curtain.open();
		this.button.pressedState();
		
		this.controller.appRouter.setCurrentWindow(this);
		
		this.isOpen = true;
	},
	
	close: function() {
		this.windowView.close();
		this.controller.curtain.close();
		this.button.defaultState();
		
		this.controller.appRouter.setCurrentWindow(null);
		
		this.isOpen = false;
	}
});


var Favorites = Backbone.Router.extend({
	initialize: function(controller, model) {
		var self = this;
		this.isOpen = false;
		this.controller = controller;
		
		this.windowView = new FavoritesView(model);
		this.button = new FavoritesButton();
		
		this.button.view.click(function() { 
			self.toggleState();
		});
	},
	
	toggleState: function() {
		var self = this;
		
		if (this.isOpen) {
			this.close();	
		} else {
			this.open();	
		}
	},
	
	open: function() {
		if (this.controller.appRouter.getCurrentWindow() != null) {
			this.controller.appRouter.getCurrentWindow().close();
		}
		
		this.windowView.open();
		this.controller.curtain.open();
		this.button.pressedState();
		
		this.controller.appRouter.setCurrentWindow(this);
		
		this.isOpen = true;
	},
	
	close: function() {
		this.windowView.close();
		this.controller.curtain.close();
		this.button.defaultState();
		
		this.controller.appRouter.setCurrentWindow(null);
		
		this.isOpen = false;
	}
});


var ShoppingCartView = DropdownView.extend({
	el: '#shoppingCartWindow',
	
	initialize: function(model) {
		var self = this;
		this.init('shoppingCart', this);
		this.model = model;
		
		
		this.model.bind('change:addToShoppingCart', this.add, this);
		this.model.bind('change:removeFromShoppingCart', this.remove, this);
		
		
		this.itemsInCart = 0;
		
		this.setNotification(itemsInCart);
		this.setBalance(shoppingCartBalance);
		
		/*
		if (self.checkIfEmpty()) {
			$('#shoppingCartWindow .checkout').hide();
		}
		*/
		
		this.preloadImages();
	},
	
	add: function() {
		var self = this;
		//alert('adding - id: ' + this.model.id);
		
		var id = this.model.id;
		
		$.ajax({
			url: url('search-results.php', 'addtocart'),
			data: 'itemID=' + id + '&wosid=' + wosid,
			error: function() {
				//alert('error');
			},
			success: function(response) {
				$('#shoppingCartWindow .content').html(response);
				self.setNotification(itemsInCart);
				self.setBalance(shoppingCartBalance);
				self.checkIfEmpty();
			}
		});
	},
		
	remove: function() {
		var self = this;
		var id = this.model.id;
		
		$('#shoppingCartItem' + id).fadeOut(500, function() { 
			$(this).remove(); 
		});
		
		$.ajax({
			url: url('search-results.php', 'removefromcart'),
			data: 'itemID=' + id + '&wosid=' + wosid,
			error: function() {
				alert('error');
			},
			success: function(response) {
				var count = $(response).find('#count');
	
				if (count.length > 0) {
					self.setNotification(count.html());
					//self.checkIfEmpty();
					
					if (self.checkIfEmpty()) {
						$('#shoppingCartWindow .checkout').hide();
					}
				} else {
					$('#shoppingCartWindow .content').html(response);
				}
			}
		});
	},
	
	setNotification: function(items) {
		this.itemsInCart = items;
		if (this.itemsInCart > 0) {
			$('#shoppingCartIndicator').show('scale', 100);
			$('#shoppingCartIndicator span').html(items);
		} else {
			$('#shoppingCartIndicator').hide();
		}
	},
	
	setBalance: function(balance) {
		$('#shoppingCartBalance').html(balance);
	},
	
	preloadImages: function() {
		var buttonShoppingCartMO = new Image(34, 30);
		buttonShoppingCartMO.src = imagePath() + 'button-shoppingcart-mo.jpg';
		
		var buttonShoppingCartMC = new Image(34, 30);
		buttonShoppingCartMC.src = imagePath() + 'button-shoppingcart-mc.jpg';
	}
});


var InfoPanelView = Backbone.View.extend({
	el: '#infoPanel',
	
	initialize: function() {
		var self = this;
		self.resize();
		$(window).bind('resize', this.resize);
	},
	
	resize: function() {
		$('#infoPanel').css({ height: ($(window).height() - $('#infoPanel').offset().top) + 'px' });
		$('#infoContent').css({ height: ($(window).height() - $('#infoContent').offset().top) + 'px' });
	},
	
	unbindEvents: function() {
		$(window).unbind('resize', this.resize);
	}
});


var ImageViewer = Backbone.View.extend({
	el: '#imageViewer',
	
	initialize: function() {
		var self = this;
		//self.ratio = $('#mainImage').width() / 160;
		self.ratio;
		self.panWidth = 160;
		self.zoomedIn = false;
		self.imageOrder = 0;
		
		self.zoomedImageWidthSmallerThanViewport = false;
		self.zoomedImageHeightSmallerThanViewport = false;
		
		//$('#buttonZoom').bind('click', this.zoomIn);
		$('#buttonZoomIn').click(function() {
			self.zoomIn();
		});
		
		$('#buttonZoomOut').click(function() {
			self.zoomOut();
		});
		
		/*
		$('#controlsZoomedIn').click(function() {
			self.zoomOut();
		});*/
		
		$('#mainImage').bind('dblclick', { self: this }, this.imageMoveToMouseCoordinates);
		$('#panSurface').bind('click', { self: this }, this.panBoxMoveToMouseCoordinates);
		
		$('.buttonPrevious').click(function() {
			self.previousImage();
		});
		
		$('.buttonNext').click(function() {
			self.nextImage();
		});
		
		this.resize();
		$(window).bind('resize', { self: this }, this.resize);
		
		this.panControls();
		
		$(window).bind('keyup', { self: this }, this.keyPressHandler);
		
		$(window).bind('resize', { self: this }, this.calculateImageSizes);
		
		//$('#panSurface').bind('click', this.positionImage);
		self.preloadImages();
	},
	
	imageMoveToMouseCoordinates: function(event) {
		var self = event.data.self;
				
		var mousePositionX = event.pageX - $(this).offset().left;
		var mousePositionY = event.pageY - $(this).offset().top;
		
		var panBoxCenterFromTop = $('#panBox').height() / 2;
		var panBoxCenterFromLeft = $('#panBox').width() / 2;
		
		$('#panBox').css({ left: (mousePositionX / self.ratio) - panBoxCenterFromLeft + 'px' });
		$('#panBox').css({ top: (mousePositionY / self.ratio) - panBoxCenterFromTop + 'px' });
		
		self.moveImage(true);
	},
	
	panBoxMoveToMouseCoordinates: function(event) {
		var self = event.data.self;
				
		var mousePositionX = event.pageX - $(this).offset().left;
		var mousePositionY = event.pageY - $(this).offset().top;
		
		var panBoxCenterFromTop = $('#panBox').height() / 2;
		var panBoxCenterFromLeft = $('#panBox').width() / 2;
		
		$('#panBox').css({ left: (mousePositionX) - panBoxCenterFromLeft + 'px' });
		$('#panBox').css({ top: (mousePositionY) - panBoxCenterFromTop + 'px' });
		
		self.moveImage(true);
	},
	
	keyPressHandler: function(event) {
		var self = event.data.self;
		
		if (event.keyCode == 90) {
			self.zoomModifier();
		}
		
		if ((event.keyCode == 39) || (event.keyCode == 40)) {
			self.nextImage();
		}
		
		if ((event.keyCode == 37) || (event.keyCode == 38)) {
			self.previousImage();
 		}
		
		if (event.keyCode == 27) {
			if (self.zoomedIn) {
				self.zoomOut();
			}
		}
	},
	
	nextImage: function() {
		var self = this;
	
		if (self.imageOrder < imagesArray.length - 1) {
			self.imageOrder++;
			self.loadImage(self.imageOrder);
		}
	},
	
	previousImage: function() {
		var self = this;
		
		if (self.imageOrder > 0) {
			self.imageOrder--;
			self.loadImage(self.imageOrder);
		}
	},
	
	zoomIn: function() {
		var self = this;
		
		self.zoomedIn = true;
		
		self.resetViewport();
		
		$('#controlsZoomedOut').fadeOut();
		$('#controlsZoomedIn').fadeIn();
		
		self.setOriginalImage();
		self.calculateImageSizes();
	},
	
	zoomOut: function() {
		var self = this;
		
		self.zoomedIn = false;
		
		self.resetViewport();
		
		$('#controlsZoomedOut').fadeIn();
		$('#controlsZoomedIn').fadeOut();
		
		self.setLargeImage();
		self.calculateImageSizes();
	},
	
	zoomModifier: function(self) {
		var self = this;
		
		if (self.zoomedIn) {
			self.zoomOut();
		} else {
			self.zoomIn();
		}
	},
	
	setLargeImage: function(imageIsFirst) {
		/*
		var self = this;
		
		$('#mainImage').width(self.imageLargeWidth);
		$('#mainImage').height(self.imageLargeHeight);
		$('#mainImage').attr('src', webPathToFiles + 'larges/' + self.imageID + '.jpg');
		*/
		
		var self = this;
		
		if (imageIsFirst != null) {
			this.imageIsFirst = imageIsFirst;
		} else {
			this.imageIsFirst = false;
		}
		
		if (imageIsFirst) {
			$('#mainImage').attr('src', webPathToFiles + 'thumbs/' + self.imageID + '.jpg');
		} else {
			$('#mainImage').attr('src', webPathToFiles + 'details/' + self.imageID + '.jpg');
		}
		
		$('#mainImage').width(self.imageLargeWidth);
		$('#mainImage').height(self.imageLargeHeight);
		
		$('#loadingMessage').show();
		var largeImage = new Image();
		largeImage.src = webPathToFiles + 'larges/' + self.imageID + '.jpg';
		$(largeImage).load(function() {
			$('#loadingMessage').hide();
			$('#mainImage').attr('src', webPathToFiles + 'larges/' + self.imageID + '.jpg');
		});
	},
	
	setOriginalImage: function() {
		var self = this;
		
		$('#mainImage').attr('src', webPathToFiles + 'larges/' + self.imageID + '.jpg');
		
		$('#mainImage').width(self.imageOriginalWidth);
		$('#mainImage').height(self.imageOriginalHeight);
		
		$('#loadingMessage').show();
		var originalImage = new Image();
		originalImage.src = webPathToFiles + 'originals/' + self.imageID + '.jpg';
		$(originalImage).load(function() {
			$('#loadingMessage').hide();
			$('#mainImage').attr('src', webPathToFiles + 'originals/' + self.imageID + '.jpg');
		});
	},
	
	loadImage: function(imageOrder) {
		var self = this;
		
		self.imageOrder = imageOrder;
		self.imageID = imagesArray[self.imageOrder][0];
		self.imageDetailsWidth = imagesArray[self.imageOrder][1];
		self.imageDetailsHeight = imagesArray[self.imageOrder][2];
		self.imageLargeWidth = imagesArray[self.imageOrder][3];
		self.imageLargeHeight = imagesArray[self.imageOrder][4];
		self.imageOriginalWidth = imagesArray[self.imageOrder][5];
		self.imageOriginalHeight = imagesArray[self.imageOrder][6];
		
		self.ratio = self.imageOriginalWidth / self.panWidth;
		
		self.setPreviewImageSelection(imageOrder);
		
		//$('#mainImage').attr('src', ''); for drag event handling (need to fix)
		$('#mainImage').remove();
		$('#viewPort').append('<img id="mainImage" />');
		
		if (this.zoomedIn) {
			self.setOriginalImage();
		} else {
			if (imageOrder == 0) {
				self.setLargeImage(true);
			} else {
				self.setLargeImage();
			}
		}
		
		self.setPanSize();
		self.resetViewport();
		self.calculateImageSizes();
	},
	
	setPreviewImageSelection: function(imageOrder) {
		$('#imagesBar img').each(function() {
			if($(this).parent().attr('class') == 'selected') {
				$(this).parent().attr('class', '');
			}
		});
		
		//$('#previewImage' + imageOrder).attr('class', 'selected');
		$('#previewImage' + imageOrder).parent().attr('class', 'selected');
	},
		
	setPanSize: function() {
		var self = this;
		
		$('#panImage').attr('src', webPathToFiles + 'details/' + self.imageID + '.jpg');
		$('#panImage').height(self.imageOriginalHeight / self.ratio);
		
		$('#panSurface').width(self.panWidth);
		$('#panSurface').height($('#panImage').height());
		$('#controlsZoomedIn').height($('#panImage').height() + $('#controlsZoomedIn .navigationButtons').height());
		
		$('#panBox').width($('#viewPort').width() / self.ratio);
		$('#panBox').height($('#viewPort').height() / self.ratio);
		
		$('#controlsZoomedIn').css({ top: ($('#viewPort').height() - $('#controlsZoomedIn').height()) / 2 });
	},
	
	panControls: function() {
		var self = this;
		
		self.inMotion = false;
				
		$('#panBox').draggable({ 
			containment: "parent",
			scroll: false,
			drag: function(event, ui) {
				//$('#mainImage').css({ top: -($(this).position().top) * ratio + 'px' });
				//$('#mainImage').css({ left: -($(this).position().left) * ratio + 'px' });
				self.moveImage();
			}
		});
		
		$('#mainImage').draggable({ 
			drag: function(event, ui) {
				self.movePanBox();
			},
			stop: function() {
				self.checkImageBounds();
			}
		});
	},
	
	moveImage: function(animated) {
		var self = this;
		
		if (animated == null) {
			animated = false;
		}
		
		if (animated) {
			$('#mainImage').animate({ top: -($('#panBox').position().top) * self.ratio + 'px', left: -($('#panBox').position().left) * self.ratio + 'px' });
		} else {
			if (!self.zoomedImageHeightSmallerThanViewport) {
				$('#mainImage').css({ top: -($('#panBox').position().top) * self.ratio + 'px' });
			}
			
			if (!self.zoomedImageWidthSmallerThanViewport) {
				$('#mainImage').css({ left: -($('#panBox').position().left) * self.ratio + 'px' });
			}
		}
	},
	
	movePanBox: function(animated) {
		var self = this;
		
		if (animated == null) {
			animated = false;
		}
		
		if (animated) {
			$('#panBox').animate({ top: -($('#mainImage').position().top) / self.ratio + 'px', left: -($('#mainImage').position().left) / self.ratio + 'px' });
			//$('#panBox').animate({ left: -($('#mainImage').position().left) / self.ratio + 'px' });
		} else {
			$('#panBox').css({ top: -($('#mainImage').position().top) / self.ratio + 'px' });
			$('#panBox').css({ left: -($('#mainImage').position().left) / self.ratio + 'px' });
		}
		
		//self.checkImageBounds();
	},
	
	checkImageBounds: function() {
		var self = this;
		
		var draggable = this;
		var inMotion = false;
		var refreshPanBox;
	
		var leftBoundary = $('#mainImage').position().left;
		var topBoundary = $('#mainImage').position().top;
		var rightBoundary = $('#mainImage').width() + $('#mainImage').position().left - $('#viewPort').width();
		var bottomBoundary = $('#mainImage').height() + $('#mainImage').position().top - $('#viewPort').height();
		
		var animationLength = 300;
		
		if ((leftBoundary > 0) && (topBoundary > 0)) {
			$('#mainImage').animate({ 
				left: 0 + 'px', 
				top: 0 + 'px' 
			}, animationLength);
			inMotion = true;
		} else if ((rightBoundary < 0) && (bottomBoundary < 0)) {
			$('#mainImage').animate({ 
				left: -($('#mainImage').width()) + $('#viewPort').width() + 'px', 
				top: -($('#mainImage').height()) + $('#viewPort').height() + 'px' 
			}, animationLength);
			inMotion = true;
		} else if ((leftBoundary > 0) && (bottomBoundary < 0)) {
			$('#mainImage').animate({ 
				left: 0 + 'px', 
				top: -($('#mainImage').height()) + $('#viewPort').height() + 'px' 
			}, animationLength);
			inMotion = true;
		} else if ((topBoundary > 0) && (rightBoundary < 0)) {
			$('#mainImage').animate({ 
				left: -($('#mainImage').width()) + $('#viewPort').width() + 'px',
				top: 0 + 'px' 
			}, animationLength);
			inMotion = true;
		} else {
			if (leftBoundary > 0) {
				$('#mainImage').animate({ left: 0 + 'px' }, animationLength);
				inMotion = true;
			} else if (topBoundary > 0) {
				$('#mainImage').animate({ top: 0 + 'px' }, animationLength);
				inMotion = true;
			} else if (rightBoundary < 0) {
				$('#mainImage').animate({ left: -($('#mainImage').width()) + $('#viewPort').width() + 'px' }, animationLength);
				inMotion = true;
			} else if (bottomBoundary < 0) {
				$('#mainImage').animate({ top: -($('#mainImage').height()) + $('#viewPort').height() + 'px' }, animationLength);
				inMotion = true;
			} else {
				self.movePanBox();
			}
		}
	
		
		if (inMotion) {
			$(draggable).bind('dragstart', function() { return false; });
			//$(draggable).draggable('disable');
			refreshPanBox = setInterval(function() { self.movePanBox(); }, 10);
			setTimeout(function() { $(draggable).unbind('dragstart'); clearInterval(refreshPanBox); }, 300);
			//setTimeout(function() { self.movePanBox(true); }, 400);
		}
	},
	
	positionImage: function(event) {
		var mousePositionX = event.pageX - $(this).offset().left;
		var mousePositionY = event.pageY - $(this).offset().top;
		
		var panBoxCenterFromTop = $('#panBox').height() / 2;
		var panBoxCenterFromLeft = $('#panBox').width() / 2;
		
		$('#panBox').css({ left: mousePositionX - panBoxCenterFromLeft + 'px' });
		$('#panBox').css({ top: mousePositionY - panBoxCenterFromTop + 'px' });
		
		//$('#panBox').draggable( "option", "refreshPositions", true);
	},
	
	resize: function(event) {
		var init = false;
		if (event != null) {
			var self = event.data.self;
			init = false;
		} else {
			var self = this;	
			init = true;
		}
		
		$('#imageViewer').css({ left: $('#infoPanel').width() });
		$('#imageViewer').width($(window).width() - $('#imageViewer').offset().left);
		$('#imageViewer').height($(window).height() - $('#imageViewer').offset().top);
		
		$('#viewPort').height($(window).height() - $('#viewPort').offset().top - $('#imagesBar').height());
		
		if (!init) {
			$('#panBox').width($('#viewPort').width() / self.ratio);
			$('#panBox').height($('#viewPort').height() / self.ratio);
			
			$('#controlsZoomedIn').css({ top: ($('#viewPort').height() - $('#controlsZoomedIn').height()) / 2 });
		}
		
		$('#controlsZoomedOut').css({ top: ($('#viewPort').height() - $('#controlsZoomedOut').height()) / 2 });
		
		//$('#panBox').width($('#viewPort').width() / self.ratio);
		//$('#panBox').height($('#viewPort').height() / self.ratio);
	},
	
	calculateImageSizes: function(event) {
		if (event != null) {
			var self = event.data.self;
		} else {
			var self = this;	
		}
		
		if (!self.zoomedIn) {
			self.scaledimageLargeWidth = self.imageLargeWidth;
			self.scaledimageLargeHeight = self.imageLargeHeight;
			self.viewPortHeight = $('#viewPort').height();
			self.viewPortWidth = $('#viewPort').width();
			
			if ($('#viewPort').height() < self.scaledimageLargeHeight) {
				//alert("height is too big");
				self.windowToImageRatio = self.scaledimageLargeHeight / $('#viewPort').height();
				
				self.scaledimageLargeHeight = $('#viewPort').height();
				self.scaledimageLargeWidth = self.scaledimageLargeWidth / self.windowToImageRatio;
			}
			
			/*/
			if ($('#viewPort').height() > self.scaledimageLargeHeight) {
				if (self.imageLargeHeight > self.scaledimageLargeHeight) {
					//alert("height is too big");
					self.windowToImageRatio = self.scaledimageLargeHeight / $('#viewPort').height();
					
					self.scaledimageLargeHeight = $('#viewPort').height();
					self.scaledimageLargeWidth = self.scaledimageLargeWidth / self.windowToImageRatio;
				}
			}*/
			
			if ($('#viewPort').width() < self.scaledimageLargeWidth) {
				//alert("width is too big");
				self.windowToImageRatio = self.scaledimageLargeWidth / $('#viewPort').width();
				
				self.scaledimageLargeWidth = $('#viewPort').width();
				self.scaledimageLargeHeight = self.scaledimageLargeHeight / self.windowToImageRatio;
			}
		
			$('#mainImage').width(self.scaledimageLargeWidth);
			$('#mainImage').height(self.scaledimageLargeHeight);
			
			$('#mainImage').css({ top: ($('#viewPort').height() - $('#mainImage').height()) / 2 });
			
			$('#mainImage').css({ left: ($('#viewPort').width() - self.scaledimageLargeWidth) / 2 + 'px' });
		} else {
			if ($('#viewPort').width() > $('#mainImage').width()) {
				//$('.header').html('wooooot');
				$('#mainImage').css({ left: ($('#viewPort').width() - $('#mainImage').width()) / 2 });
				//$('#panBox').draggable( "option", "axis", 'y' );
				self.zoomedImageWidthSmallerThanViewport = true;
				self.zoomedImageHeightSmallerThanViewport = false;
			}
			
			if ($('#viewPort').height() > $('#mainImage').height()) {
				//$('.header').html('wooooot2222');
				$('#mainImage').css({ top: ($('#viewPort').height() - $('#mainImage').height()) / 2 });
				//$('#panBox').draggable( "option", "axis", 'x' );
				self.zoomedImageHeightSmallerThanViewport = true;
				self.zoomedImageWidthSmallerThanViewport = false;
			}
			
			if (($('#viewPort').width() > $('#mainImage').width()) && ($('#viewPort').height() > $('#mainImage').height())) {
				self.zoomedImageHeightSmallerThanViewport = true;
				self.zoomedImageWidthSmallerThanViewport = true;
			}
			
			if (($('#viewPort').width() < $('#mainImage').width()) && ($('#viewPort').height() < $('#mainImage').height())) {
				self.zoomedImageHeightSmallerThanViewport = false;
				self.zoomedImageWidthSmallerThanViewport = false;
			}
		}
	},
	
	resetViewport: function() {
		$('#mainImage').css({ left: 0 + 'px'});
		$('#mainImage').css({ top: 0 + 'px'});
		
		$('#panBox').css({ left: 0 + 'px'});
		$('#panBox').css({ top: 0 + 'px'});	
	},
	
	unbindEvents: function() {
		$(window).unbind('resize', this.resize);
		$(window).unbind('keyup', this.keyPressHandler);
		$(window).unbind('resize', this.calculateImageSizes);	
	},
	
	preloadImages: function() {
		var buttonPreviousMO = new Image(28, 26);
		buttonPreviousMO.src = imagePath() + 'button-imageviewer-previous-mo.jpg';
		
		var buttonPreviousMC = new Image(28, 26);
		buttonPreviousMC.src = imagePath() + 'button-imageviewer-previous-mc.jpg';
		
		var buttonPreviousDisabled = new Image(28, 26);
		buttonPreviousDisabled.src = imagePath() + 'button-imageviewer-previous-disabled.jpg';
		
		var buttonNextMO = new Image(28, 26);
		buttonNextMO.src = imagePath() + 'button-imageviewer-next-mo.jpg';
		
		var buttonNextMC = new Image(28, 26);
		buttonNextMC.src = imagePath() + 'button-imageviewer-next-mc.jpg';
		
		var buttonNextDisabled = new Image(28, 26);
		buttonNextDisabled.src = imagePath() + 'button-imageviewer-next-disabled.jpg';
		
		var buttonZoomOutMO = new Image(48, 26);
		buttonZoomOutMO.src = imagePath() + 'button-imageviewer-zoomout-mo.jpg';
		
		var buttonZoomOutMC = new Image(48, 26);
		buttonZoomOutMC.src = imagePath() + 'button-imageviewer-zoomout-mc.jpg';
	}	
});


var CategoryOption = Backbone.View.extend({
	el: '.optionsBar',
	
	initialize: function(name) {
		var self = this;
		self.name = name;
		self.isOpen = false;
		
		self.categoryOption = $('#categoryOption' + self.name);
		self.categoryOptionDropdown = $('#categoryOptionDropdown' + self.name);
		
		self.categoryOption.click(function() { self.toggleState(); });
		
		self.resize();
		$(window).resize(function() {
			self.resize();
		});
		
		$(window).bind('click', { self: self }, self.checkClickLocation);
		self.preloadImages();
	},
	
	toggleState: function() {
		var self = this;
		
		if (self.isOpen) {
			self.close();
		} else {
			self.open();
		}
	},
	
	open: function() {
		var self = this;
		self.categoryOption.attr('class', 'categoryOptionSelected');
		self.categoryOption.children('.arrow').attr('src', imagePath() + 'option-dropdown-arrow-mc.jpg');
		self.categoryOptionDropdown.fadeIn(300);
		//alert(self.name + ' open');
		//$(window).bind('click', { self: self }, self.checkClickLocation);
		/*
		$(window).bind('click', function(event) {
			if (event.target.id != 'categoryOption' + self.name) {
				self.close();
			}
		});*/
		
		self.isOpen = true;
	},
	
	checkClickLocation: function(event) {
		//alert(event.data.self);
		var self = event.data.self;
		
		if (event.target.id != 'categoryOption' + self.name) {
			self.close();
		}
	},
	
	close: function() {
		var self = this;
		self.categoryOption.attr('class', 'categoryOption');
		self.categoryOption.children('.arrow').attr('src', imagePath() + 'option-dropdown-arrow.jpg');
		self.categoryOptionDropdown.fadeOut(300);
		
		self.isOpen = false;
		//$(window).unbind('click', self.test);
	},
	
	resize: function() {
		var self = this;
		self.categoryOptionDropdown.css({ left: (self.categoryOption.position().left + 7) + 'px' });
	},
	
	preloadImages: function() {
		var arrowMC = new Image(7, 6);
		arrowMC.src = imagePath() + 'option-dropdown-arrow-mc.jpg';
	}
});

var MainImage = Backbone.View.extend({	
	initialize: function() {
		var self = this;
	},
	
	resize: function() {
		var ratio = mainImageWidth / mainImageHeight;
		 $('#mainImage').height($('#mainImage').width() / ratio)
		 
		var imageCenter = $('#mainImage').height() / 2;
		var viewCenter = $('#main').height() / 2;
		$('#mainImage').css({ top: -imageCenter + viewCenter });
	}
});


var ContactView = Backbone.View.extend({	
	initialize: function() {
		var self = this;
	},
	
	resize: function() {
		$('#contactView').height($('#main').height());
		
		$('#aboutView').width($(window).width() - $('#contactView').width());
		$('#aboutView').height($('#main').height());
		$('#aboutView').css({ left: $('#contactView').width() });
	}
});


var CheckoutView = Backbone.View.extend({	
	initialize: function() {
		var self = this;
	},
	
	resize: function() {
		$('#checkoutItemListViewTable').height($('#main').height() - $('#bottomBar').height());
		$('#checkoutPanelView').height($('#main').height());
		
		$('#checkoutItemListView').width($(window).width() - $('#checkoutPanelView').width());
		$('#checkoutPanelView').css({ left: $('#checkoutItemListView').width() });
	}
});


function validateEmail(email)
{
	var atpos=email.indexOf("@");
	var dotpos=email.lastIndexOf(".");
	if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
		return false;
	} else {
		return true;
	}
}

