// image preload (frames and size icons)

var preload = function() {
	var frameUrl = $('base').attr('href') + "images/elements/frames/";
	var sizeUrl = $('base').attr('href') + "images/date_search/icons_size/icon_size_";

	var sizes = ['medium', 'large', 'small'];
	var frameSizes = ['small', 'classic', 'gallery', 'exhibition']; 
	var orientations = ['landscape', 'portrait'];
	var materials = ['birch', 'black', 'silver', 'light-wood', 'dark-wood', 'palisander'];
	
	for(var i = 0; i < sizes.length; i++) {
		for(var j = 0; j < orientations.length; j++) {
			for(var k = 0; k < materials.length; k++) {
				var image = new Image();
				image.src = frameUrl + orientations[j] + '-' + sizes[i] + '-' + materials[k] + '.jpg';
			}
		}
	}
	
	for(var i = 0; i < frameSizes.length; i++) {
		for(var j = 0; j < orientations.length; j++) {
			var image = new Image();
			image.src = sizeUrl + frameSizes[i] + '_' + orientations[j] + '.png';
		}
	}
}();

$(document).ready(function() {
	var displayedDay = SideCalendar.getDate();
	
	// character counters and example images
	$('#occasion').children().each(function() {
	  var sector = $(this).attr('value');
	  CharacterCounter($('#message-'+sector), $('#message-chars-'+sector));
	  
	  $('#example-'+sector).click(function() {
	    var position = {left: 0, top: 0};
		position.left = $(window).width()/2 - 300;
		position.top = $(window).height()/2 - 201;
		
	  	window.open(this.href,'_blank','width=640,height=432,left='+position.left+',top='+position.top+',toolbar=no,menubar=no,location=no');
	    return false;
	  });
	});
	
	// personalisation popup
	var popup = Popup('.popup', ['.popup :submit', '.popup :image', '.popup #close-popup']);
	
	var parentShow = popup.show;
	popup.show = function(source) {
		popup.openedBy = source;
		parentShow(source);
	};
	
	var parentHide = popup.hide;
	popup.hide = function(source) {
		var openedByPurchase = $(popup.openedBy).attr('id') == 'purchase-image';
		var closedBySubmitMessage = $(source).attr('id') == 'save';
		var messageFieldFilled = $('#message-' + $('#occasion').val()).val() != '';
		
		if(openedByPurchase && closedBySubmitMessage && messageFieldFilled) {
			$('#purchase-image').click();
			$('#purchase-image').get(0).disabled = true;
		}
		
		parentHide(source);
		
		return false;
	};
	
	// create a loading layer that will hide the main image when changing image number
	var loadingLayer = $(document.createElement('div')).attr('id', 'loading-layer').appendTo('#photograph_container');
	$('#photograph_container img').load(function() { loadingLayer.fadeOut(); });
	
	// Handle clicking on the date list
	$('#days_container .month-days a').live("click", function() {
		displayedDay = null;
		
		SideCalendar.setDay(parseInt($(this).text()));
		SideCalendar.loadSelectedDay();
		
  		return false;
	});
	
	// Handles clicking on frame type list
	$('#frame-types input[type=radio]').click(function() {
		$('#photograph_container').removeClass('wood').removeClass('silver').removeClass('black').removeClass('light-wood').removeClass('dark-wood').removeClass('palisander')
			.addClass($(this).val());
		var thisLi = $(this).parent().parent();
		thisLi.parent().find('li.selected').removeClass('selected');
		thisLi.addClass('selected');
		
		// update enlarge link
		var enlarge = $('#photograph_container a');
		var href = enlarge.attr('href');
		if(href.match(/frame\-type/) != null) {
			href = href.replace(/frame\-type\/([\w\-]+)/, "frame-type/" + $(this).val());
		} else {
			href = href + "/frame-type/" + $(this).val();
		}
		enlarge.attr('href', href);
	});
	
	// Handles clicking on size list
	$('#frame-sizes input[type=radio]').click(function() {
		var thisLi = $(this).parent().parent();
		var prevSelected = thisLi.parent().parent().find('li.selected').removeClass('selected');
		thisLi.addClass('selected');
		
		// update parent ul class
		thisLi.parent().attr('class', $(this).val());
		
		// update frame types list
		$('#frame-types li').hide().filter('li[class*=' + $(this).val() + ']').show();
		$('#frame-types input').attr('disabled', 'disabled').filter('input:visible').removeAttr('disabled');

		if($('#frame-types input:hidden:checked').size() > 0) {
		  $($('#frame-types input:visible').get(0)).click();
		}
		
		// update enlarge link
		var enlarge = $('#photograph_container a');
		var href = enlarge.attr('href');
		if(href.match(/frame\-size/) != null) {
			href = href.replace(/frame\-size\/(\w+)/, "frame-size/" + $(this).val());
		} else {
			href = href + "/frame-size/" + $(this).val();
		}
		enlarge.attr('href', href);
	});
	
	$('#frame-sizes input:checked').click(); // simulate the first click to hide the unwanted frame types
	
	// Handles clicking on other images of the day
	$('#daily-photos img').live("click", function() {
		var mainImage = $('#photograph_container img');
		var orientation = $(this).attr('class');
		
		// hide old image
		loadingLayer
			.css(mainImage.offset())
			.removeClass('portrait').removeClass('landscape').addClass(orientation)
			.show();
		
		// load new image
		var src    = mainImage.attr('src');
		var number = $(this).attr('src').match(/number\/(\d+)/)[1];
		
		if(src.match(/number/) != null) {
			src = src.replace(/number\/(\d+|photo-of-the-day)/, "number/" + number);
		} else {
			src = src + "/number/" + number;
		}
		mainImage
			.removeClass('portrait').removeClass('landscape').addClass(orientation)
			.attr('src', src);
			
		// update the 'enlarge' link
		var href = mainImage.prev().attr('href');
		if(href.match(/number/) != null) {
			href = href.replace(/number\/(\d+|photo-of-the-day)/, "number/" + number);
		} else {
			href = href + "/number/" + number;
		}
		mainImage.prev().attr('href', href);

		// update the frame size list if necessary (based on orientation)
		if($('#frame-sizes ul:visible').parent().attr('id').match(orientation) == null) {
			var frameSize = $('#frame-sizes input:checked').val();
			$('#frame-sizes ul').toggle().filter('ul:visible').find('input[value=' + frameSize + ']').click();
		}
		
		// update mailto img nbr l%2Fp
		var href = $('#email-friend a').attr('href');
		if(href.match(/number/) != null) {
			href = href.replace(/number%2F(\d+|photo-of-the-day)/, "number%2F" + number);
		} else {
			href = href + "%2Fnumber%2F" + number;
		}
		$('#email-friend a').attr('href', href);

		return false;
	});
	
	// Handle enlarge popup
	$('#photograph_container a').click(function() {
		// choose window size depending on whether the image is portrait or landscape
		var size = {width:736, height:610};
		if($(this).next().hasClass('portrait')) {
			size.width = 610;
			size.height = 750;
		}
		
		// center on screen
		var position = {left: 0, top: 0};
		position.left = $(window).width()/2 - size.width/2;
		position.top = $(window).height()/2 - size.height/2;
		
		window.open(this.href,'_blank','width='+size.width+',height='+size.height+',left='+position.left+',top='+position.top+',toolbar=no,menubar=no,location=no');
		return false;
	});	
	
	// PERSONALISE POPUP

	// Handles changing the popup select value
	$('#personalise #occasion').change(function() {
		$(this).parent().parent().parent().children('tr[class!=]').hide().filter('tr.'+$(this).val()).show();
	});
	$('#personalise #occasion').change(); // make sure the appropriate elements will be hidden
	
	// Handles clicking on "personalise" link
	$('#personalise #open-popup').click(function() {
		popup.show(this);
		return false;
	});

	// Handles clicking on "purchase image" button
	$('#purchase-image').click(function() {
		if(displayedDay == null) {
			return;
		}
		
		// check if cookies are enabled
		document.cookie = "thedaythat-test=thedaythat-test; path=/";
		if(document.cookie.search(/thedaythat-test=/i) == -1) {
			alert("You need to enable cookies in your browser in order to use the basket");
			return;
		} else {
			document.cookie = "thedaythat-text=;expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
		}
	
		var sector = $('#occasion').val();
		
		// if not personalised:
		if($('#message-' + sector).val() == '') {
		
			// Display the error message
			$('.popup .error').show();
			
			// Open the personalisation popup
			popup.show(this);
			
			// break flow
			return;
		}
	
		var imgSrc = $('#photograph_container img').attr('src');
		var baseUrl = $('base').attr('href');
		var number  = (imgSrc.match(/number/) != null ? imgSrc.match(/number\/(\d+|photo-of-the-day)/)[1] : 'photo-of-the-day');
		
		if(number == 'photo-of-the-day') {
			number = SideCalendar.getPhotoOfTheDayNumber(displayedDay.getDate(), displayedDay.getMonth() + 1, displayedDay.getFullYear());
		}
		
		var params  = {
			'format': 'json',
			'item-type': 'photo',
			'day': displayedDay.getDate(),
			'month': displayedDay.getMonth() + 1,
			'year': displayedDay.getFullYear(),
			'number': number,
			'frame-type': $('input[name^=frame-type]:checked').val(),
			'frame-size': $('input[name^=frame-size]:checked').val(),
			'message-sector': sector,
			'message': $('#message-' + sector).val()
		};
		
		$.getJSON(baseUrl + "basket/add", params, function(data) {
			if(data.success)
				window.location.href = baseUrl + "basket";
			else
				alert('There was a problem when adding to the basket, please try again');
		});
		
		return false;
	});
});

