/*==============================================
 Web Fonts
 ===============================================*/
WebFontConfig = {
	google: { families: [ 'IM Fell DW Pica:regular,italic', 'Homemade Apple' ] }
};
(function() {
	var wf = document.createElement('script');
	wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
			'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
	wf.type = 'text/javascript';
	wf.async = 'true';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(wf, s);
})();

/*===============================================
 Helpers
 ===============================================*/
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};
Array.prototype.findIndex = function(value) {
	for (var i = 0; i < this.length; i++) {
		if (this[i]['sku'] == value) {
			return i;
		}
	}
	return -1;
};

/*===============================================
 All jQuery
 ===============================================*/
$(function() {
	/*=============
	 Moderniz-ation
	 =============*/
	if (!Modernizr.backgroundsize) {
		$('body').prepend('<img class="main-bg" src="/images/main_bg.jpg" alt="background"/>');
	}
	if (!Modernizr.multiplebgs) {
		$('.wrapper').prepend('<div class="wrapper-border-L"></div><div class="wrapper-border-R"></div>');
	}
	if (!Modernizr.borderimage) {
		$('.subnav').append('<div class="subnav-border-l"></div><div class="subnav-border-r"></div><div class="subnav-border-b"></div>');
	}

	/*===========
	 Design Board
	 ============*/
	$('.design-board-tab, .design-board-overlay').click(toggleDesignBoard);
	$('div.swatch').click(makeSelection);
	$('.design-board-add').click(addToDesignBoard);
	$('.design-board-remove').live('click', removeFromDesignBoard);
	$('.design-board-download').click();
	$('.design-board-print').click(function(event) {
		event.preventDefault();
		event.stopPropagation();
		window.open(this.href, '_blank');
	});
	$('.design-board-email').click(function(event) {
		event.preventDefault();
		event.stopPropagation();
		window.open(this.href, 'popWin', 'width=420,height=420');
	});
	resetAddButton();
	setDesignBoardLabel();

	function toggleDesignBoard() {
		var scrollableArea = $('.design-board-items');
		var body = $('body');
		scrollableArea.height((body.height() - $('.design-board-tab').height() - $('.design-board-head').height()) * .8);
		$('.design-board-overlay').height($(document).height()).toggle();
		$('.design-board').slideToggle('slow', function() {
			if ($(this).is(':visible')) {
				scrollableArea.jScrollPane();
			}
		});
		body.toggleClass('noscroll');
		$('.design-board-arrow').toggleClass('up');
	}

	// the user makes a selection from either fabric or finish sections
	function makeSelection() {
		// make selection
		var addButton;
		if ($(this).attr('data-type') == 'fabric') {
			$('#fabric-image').attr('src', $(this).attr('data-limage')).attr('alt', $(this).attr('data-name'));
			$('#fabric-sku').html($(this).attr('data-sku'));
			$('#fabric-cleaning-code').html($(this).attr('data-cleancode')).attr('href', '#');
			$('#fabric-notes').html($(this).attr('data-content'));
			addButton = $('#fabric-add-button');
		} else {
			$('#finish-image').attr('src', $(this).attr('data-limage')).attr('alt', $(this).attr('data-name'));
			$('#finish-sku').html($(this).attr('data-name') + ' (' + $(this).attr('data-sku') + ')');
			addButton = $('#finish-add-button');
		}
		addButton.attr('data-type', $(this).attr('data-type'))
				.attr('data-sku', $(this).attr('data-sku'))
				.attr('data-name', $(this).attr('data-sku'))
				.attr('data-image', $(this).attr('data-limage'));
		// reset add button
		resetAddButton();
	}

	// cookie key for the design board contents
	function getKey() {
		return 'designboard';
	}

	// shows how many items in the design board
	function setDesignBoardLabel() {
		var db = getDesignBoard();
		var total = 0;
		for (var prop in db) {
			if (db.hasOwnProperty(prop)) {
				total += db[prop].length;
			}
		}
		$('#design-board-counter').html('(' + total + ')');
	}

	// returns a design board
	function getDesignBoard() {
		// barebone structure
		var designBoard = {product: [], fabric: [], finish: []};
		// create a new design board
		if ($.cookie(getKey()) == null) {
			saveDesignBoard(getKey(), designBoard);
		}
		return $.evalJSON($.cookie(getKey()));
	}

	// save the design board to cookie
	function saveDesignBoard(key, val) {
		$.cookie(key, $.toJSON(val), {expires: 7, path: '/'});
	}

	// add the given item to the design board
	function addToDesignBoard(e) {
		// stop all other things... and leave it to me
		e.preventDefault();
		// parse data
		var type = $(this).attr('data-type');
		var sku = $(this).attr('data-sku');
		var name = $(this).attr('data-name');
		var image = $(this).attr('data-image');
		// you never know...
		if (type.length < 1 && sku.length < 1) {
			return false;
		}
		// get the design board
		var designBoard = getDesignBoard();
		// see if the given item exists in the design board
		var idx = designBoard[type].findIndex(sku);
		if (idx > -1) {
			if (!$(this).hasClass('already-added')) {
				$(this).addClass('already-added');
				alert("This item is already in design board.");
			}
			return false;
		}
		// add it
		designBoard[type].push({ sku: sku, name: name, image: image });
		// save it
		saveDesignBoard(getKey(), designBoard);
		//insert into design board
		var container, imgWidth, imgHeight, toAppend;
		if (type == 'product') {
			container = '.my-styles';
			imgWidth = 235;
			imgHeight = 145;
		} else if (type == 'fabric') {
			container = '.my-fabrics';
			imgWidth = 145;
			imgHeight = 145;
		} else if (type == 'finish') {
			container = '.my-finishes';
			imgWidth = 103;
			imgHeight = 103;
		}
		toAppend = '<div class="design-board-item">';
		toAppend += '<img src="' + image + '" width="' + imgWidth + '" height="' + imgHeight + '" alt="' + name + '" name="' + sku + '"/>';
		toAppend += '<p class="design-board-meta">';
		toAppend += '<span class="design-board-sku">' + (type == 'finish' ? name + ' (' + sku + ')' : sku) + '</span>';
		if (type == 'product') {
			toAppend += '<span class="design-board-itemname">' + name + '</span>';
		}
		toAppend += '</p><a href="#" class="design-board-remove" data-type="' + type + '" data-sku="' + sku + '">X</a></div>';

		$(container).append(toAppend);
		// update design board count label
		setDesignBoardLabel();
		// reset add button
		resetAddButton();
		// page doesn't get refreshed
		return false;
	}

	// delete the given item from the design board
	function deleteFromDesignBoard(type, sku) {
		// get the design board
		var designBoard = getDesignBoard();
		// see if the given product exists in the design board
		var idx = designBoard[type].findIndex(sku);
		if (idx == -1) {
			alert("This item doesn't exist in design board."); // for debugging
			return false;
		}
		// delete it
		designBoard[type].remove(idx);
		// save it
		saveDesignBoard(getKey(), designBoard);
		// successful removal
		return true;
	}

	// remove the item from the design board (visual & data)
	function removeFromDesignBoard(e) {
		// stop all other things... and leave it to me
		e.preventDefault();
		// remove it
		if (deleteFromDesignBoard($(this).attr('data-type'), $(this).attr('data-sku'))) {
			$(e.target).parents('.design-board-item').hide();
			setDesignBoardLabel();
		}
		// reset add button
		resetAddButton();
	}

	// resets all add buttons on the page
	function resetAddButton() {
		var designBoard = getDesignBoard();
		$('.design-board-add').each(function() {
			var type = $(this).attr('data-type');
			var sku = $(this).attr('data-sku');
			if (type.length > 0 && sku.length > 0) {
				if (designBoard[type].findIndex(sku) < 0) {
					$(this).removeClass('already-added');
				} else {
					$(this).addClass('already-added');
				}
			}
		});
	}

	/*============
	 Forms
	 =============*/
	$('#contact-clear').click(function(e) {
		var parent = $(e.target).parents('form');
		parent[0].reset();
		e.preventDefault();
	});

	/*=============
	 Store Locator Results Tables
	 ==============*/
	$('.location-list tr:even').addClass('even-row');

});
