$(document).ready(function(){
	/*
	$.get('/router.cfm',
		{
			ajax: true,
			format: 'json',
			source: 'js'
			
		},
		function(obj){}
	);*/
	
	// check browser width and hide xmas images if not wide enough
	if($(window).width() < 1350) {
		$(".container").css("background","none");
		$(".secondary-container").css("background","none");
	}
	
	// bind handler for change event on Browse select list 
	// on personalised HP 1
	$('#portal_category').bind("change", function(event){
		self.location.href = $('#portal_category option:selected').val();
	});
	
	$('#footer').shopButtons();													// handler for the footer buttons
	$('#slide-container').rightColSlider();										// handler for the right hand column sliding offers
	
	$('#personalised-sections > div').each(function(){							// handler for the slideways scrolling sections on the "Long Generic" pages
		$(this).customisedSlidingSection();				
	});
	
	$('#footer_newsletter-email').focus(function(){								// turn text in the email field black
		if($(this).val() == 'email') {
			$(this).val('');
			$(this).css('color','#000000');
		}
	});
	
	$('#col-1and2 .panel-cycle').cycle({										// handler for the carousel on "Short Generic"
    	fx: 'scrollHorz',
    	timeout: 6000,
    	speed: 2000,
    	pauseOnPagerHover: 1,
    	pager: '.hp-carousel-tabs',
    	height: 395,
    	width: 727
    });
	
	$('#col-2and3 .panel-cycle').cycle({										// handler for the carousel on "Long Generic"
    	fx: 'scrollHorz',
    	timeout: 6000,
    	speed: 2000,
    	pauseOnPagerHover: 1,
    	pager: '.hp-carousel-tabs',
    	height: 358,
    	width: 759
    });
});

jQuery.fn.extend({
	
	/**
	 * Behaviour for the shop button rollovers
	 * @return jQuery
	 */
	shopButtons: function() {
		var dst = this;
		
		$('#expando-rollover a',$(this)).mouseleave(function(){
			$('#expando-rollover a',$(dst)).hide();
		});
		
		$('#expando a',$(this)).mouseenter(function(){
			$('#expando-rollover a',$(dst)).hide();
			var targetClass = $(this).attr('class');
			$('#expando-rollover .'+targetClass,$(dst)).show();
		});
		
		return this;
	},
	
	/**
	 * Handler to do the right hand column slider - slides in 3 offers every [x] seconds
	 * @return jQuery
	 */
	rightColSlider: function() {
		var dst = this;
		
		var currentSlide = 0;
		var totalSlides = Math.ceil($('.slide-set .slide',$(dst)).size()/3);
		var marginOffset = $('.slide-set',$(dst)).height();
		var marginOffsetDirection = '-=';
		
		var slide = function(direction) {
			trace(direction);
			switch(direction){
				case 'up':
					marginOffsetDirection = '+=';
					currentSlide--;
					break;
					
				case 'down':
					marginOffsetDirection = '-=';
					currentSlide++;
					break;
			}
			trace(currentSlide);
			if(currentSlide <= 0) {
				$('#slide-nav-up',$(dst)).removeClass('enabled');
			} else {
				$('#slide-nav-up',$(dst)).addClass('enabled');
			}
			
			if(currentSlide >= totalSlides-1){
				$('#slide-nav-down',$(dst)).removeClass('enabled');
			} else {
				$('#slide-nav-down',$(dst)).addClass('enabled');
			}
			
			$('.slide-set',$(dst)).first().animate({
				marginTop: marginOffsetDirection+marginOffset
			});
		}
		
		$('#slide-nav a').bind('click',function(){
			if($(this).hasClass('enabled')){
				slide($(this).attr('href').substr(1));
			}
			
			return false;
		});
	},
	
	/**
	 * Handler for the navigation etc of the sideways scrolling sections
	 * @return jQuery
	 */
	customisedSlidingSection: function() {
		var dst = this;																			// save a reference to the container
		var typeID = 1;																			// typeID 1 is magazines etc - from the db
		var currentPage = 1;																	// what page are we currently looking at
		var totalPages = 1;																		// how many pages are there in total
		var sectionWidth = $('.section-container',$(dst)).width();								// how much to move the tables left and right when clicked
		
		switch($(dst).attr('class')) {
			case 'newspapers': typeID = 2; break;
			case 'holiday-brochures': typeID = 9; break;
			case 'magazines-from-abroad': typeID = 11; break;
			case 'retail-catalogues': typeID = 15; break;
			case 'travel-guides': typeID = 13; break;
			default: typeID = 1; break;
		}
		
		var resetNav = function() {																// re-enable nav as required when animation finishes
			$('.next',$(dst)).removeClass('animating');											// remove the animating flags
			$('.previous',$(dst)).removeClass('animating');
			
			if(currentPage >= totalPages) {														// disenable the next button if we're on the last page
				$('.next',$(dst)).addClass('disabled');
			} else {
				$('.next',$(dst)).removeClass('disabled');
			}
			
			if(currentPage <= 1) {																// disenable the previous button if we're on page 1
				$('.previous',$(dst)).addClass('disabled');
			} else {
				$('.previous',$(dst)).removeClass('disabled');
			}
		}
		
		var loadSet = function(direction) {														// handler for loading the tables to display
			
			$.ajax({
				url: '/services/local/portal/popular.cfm',
				data: {typeID:typeID,page:currentPage,prodGroupId:prodGroups[typeID]},
				success: function(data) {
					
					switch(direction) {
						case 'first':															// first table, so just swipe it in
							var target = $(data).appendTo($('.slide-contents',$(dst)));			// add the new table at the end
							$(target).animate({ marginLeft: 0 },1000);							// swipe in from left
							resetNav();
							break;
							
						case 'next':
							var oldTable = $('table:first-child',$(dst));
							var target = $(data).appendTo($('.slide-contents',$(dst)));
							
							$(target).css('marginLeft',0);										// set to just float
							$(oldTable).animate(												// swipe old out to the left
								{ marginLeft: sectionWidth*-1 },
								1000,
								function() {													// then remove it from the dom
									$(this).remove();
									resetNav();
								}
							);
							break;
							
						case 'previous':
							var oldTable = $('table:first-child',$(dst));
							var target = $(data).prependTo($('.slide-contents',$(dst)));
							
							$(target).css('marginLeft',sectionWidth*-1);						// set to be off to the left of the screen
							
							$(target).animate(													// swipe old out to the left
								{ marginLeft: 0 },
								1000,
								function() {													// then remove it from the dom
									$(oldTable).remove();										// and remove the old table
									resetNav();
								}
							);
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					trace(errorThrown);
				}
			});
		};
		
		$('.personal-section-nav',$(this)).bind('click',function(){								// click handlers for the next / previous nav
			
			if($(this).hasClass('next')) {														// slide the contents left
				if(!$(this).hasClass('disabled') && !$(this).hasClass('animating')) {
					currentPage++;																// increment the page we are looking at
					$('.personal-section-nav',$(dst)).addClass('animating');					// disable nav while swiping
					loadSet('next');
				}
			}
			
			if($(this).hasClass('previous')) {													// slide the contents right
				if(!$(this).hasClass('disabled') && !$(this).hasClass('animating')) {
					currentPage--;																// decrementincrement the page we are looking at
					$('.personal-section-nav',$(dst)).addClass('animating');					// disable nav while swiping
					loadSet('previous');
				}
			}
			
			return false;
		});
		
		$.ajax({																				// load the initial data about how mang pages of results we have
			url: '/services/local/portal/popular.cfm?mode=meta&typeID='+typeID,
			dataType: 'json',
			success: function(data){
				totalPages = data.totalPages;													// set how many sets of 6 we have to display
				
				if(totalPages == 0) {															// if there are 0 pages, then there was no error, but their are also no results
					$(dst).remove();
					return;
				}
				
				if(totalPages > 1) {															// more than 1 means the next button needs to be enabled
					$('.next',$(dst)).removeClass('disabled');
				} 
				
				loadSet('first');
			},
			error: function(jqXHR, textStatus, errorThrown) {									// if we get no ggod data, remove the whole section
				$(dst).remove();
			}
		});
	}
});

/**
 * Fuck-up prevention; checks to see if the console exists before posting to it,
 * so that console.log messages that are accidentally left in do not break a
 * page when run live. Called "trace" as I have been doing a lot of AS3 today
 * and I keep typing it anyway
 * @param message
 * @return void
 */
function trace(message) {
    if(typeof(console) != 'undefined' && typeof(console.log) == 'function') {
	console.log(message);
    }
}
