/* thecollectorate.net */

;(function($){

	$.collectorateUpdatePrice = function () {

		// dynamic pricing
		//$.dynamicPricing('item');

		// remember options, item page to section page by using cookie
		/* cookie data array format:
			data =	[	[ item1Id, optionName, optionValue ],
						[ item2Id, optionName, optionValue ]
					]
		*/

		var currency				= '$'
		var delimiter 				= '_o0_';
		var subdelimiter 			= '_o1_';
		var formValueCookieName 	= 'collectoratevalues';
		var formSel					= '.addtocart-form';
		var idSel					= '.item-id';
		var priceSel				= '.price .amount, .price-bold .amount';
		var salePriceSel			= '.sale-price .amount, .sale-price-bold .amount';
		var optionsSel				= 'select';
		var checkboxSel				= '.multi-add-checkbox';
		var checkboxPriceSel		= '.multi-add-price .amount';

		function formatPrice (priceAmount) {
			var price = new Number(priceAmount);
			return currency + price.toFixed(2);
		}

		function getPriceAmount (jPrice) {
			var text = jPrice.text();
			if (!text) { return null; }
			// remove dollar sign
			return text.replace(/\$/, '');
		}
	
		function formValueCookieRead () {			
			var dataArr;
			var dataStr = $.cookie(formValueCookieName);
			if (dataStr) {
				dataArr = arrayParse(dataStr);
			} else {
				dataArr = [];
			}
			return dataArr;
		}

		function formValueCookieUpdate (itemId, name, value) {
			// read cookie
			var dataArr = formValueCookieRead();
			// update array
			// update existing value
			var found = false;
			for (var i=0;i<dataArr.length;i++) {
				if (dataArr[i][0] == itemId && dataArr[i][1] == name) {
					//dataArr[i][2] = escape(value.replace('+', '{plus}'));
					dataArr[i][2] = value.replace('+', '{plus}');
					found = true;
					break;
				}
			}
			// add value
			if (!found) {
				var len = 0;
				if (dataArr.length) { len = dataArr.length; }
				dataArr[len] 	= [];
				dataArr[len][0] = itemId;
				dataArr[len][1] = name;
				dataArr[len][2] = value;
			}
			// write cookie
			var dataStr = arrayStringify(dataArr);
			var opts = {	'hours'		: 100,
							'path'		: '/' };
			$.cookie(formValueCookieName, dataStr, opts);
		}

		function arrayStringify (arr) {
			var a = arr;
			var s = '';
			if (typeof arr === 'object') {
				for (var i=0;i<arr.length;i++) {
					a[i] = arr[i] ? arr[i].join(subdelimiter) : '';
				}
				s = a.join(delimiter)
			}
			return s;
		}

		function arrayParse (str) {
			var a = [];
			var s = str;
			if (typeof s === 'string') {
				a = str.split(delimiter);
				for (var i=0;i<a.length;i++) {
					a[i] = a[i] ? a[i].split(subdelimiter) : null;
				}
			}
			return a;
		}

		function getCookieValue (dataArr, itemId, name) {
			// loop through data
			for (var i=0;i<dataArr.length;i++) {
				// if match item id and option name
				if (dataArr[i][0] == itemId && dataArr[i][1] == name) {
					return dataArr[i][2];
				}
			}
			// else
			return null;
		}

		function updatePrice (jForm) {
			// get price object, base price
			var jPrice = jForm.find(priceSel);
			var price = jPrice.data('price');
			// get sale price object, base price
			var jSalePrice = jForm.find(salePriceSel);
			var salePrice = jSalePrice.data('price');
			if (price > 0 || salePrice > 0) {
				// get price differential total
				// start with checkbox price
				var checkboxTotal =		jForm.find(checkboxSel).is(':checked')
										? jForm.find(checkboxPriceSel).data('price')
										: 0;
				// add total options price
				var diffOption = 0;
				jForm.find(optionsSel).each(function(){
					var diff = $(this).val();
					diff = diff.match(/\((.*)\)/);
					diff = diff ? parseFloat(diff[1]) : 0;																 
					diffOption = diffOption + diff;
				});
				// set price
				jPrice.text(formatPrice((price * 1) + (checkboxTotal * 1) + (diffOption * 1)));
				// set sale price
				jSalePrice.text(formatPrice((salePrice * 1) + (checkboxTotal * 1) + (diffOption * 1)));
			}
		}

		// --------------------------------------------------------------------
		// end functions

		// get data from cookie
		var dataArr = formValueCookieRead();

		// ----------------------------------------------------------------
		// each addtocart form
		$(formSel).each(function(i, elem){

			// set form object		
			var jForm = $(elem);
			var jPrice;

			// initialize price data()
			// item price
			jPrice = jForm.find(priceSel);
			if (!(jPrice.data('price') > 0)) {
				jPrice.data('price', getPriceAmount(jPrice));
			}
			// item sale price
			jPrice = jForm.find(salePriceSel);
			if (!(jPrice.data('price') > 0)) {
				jPrice.data('price', getPriceAmount(jPrice));
			}
			// checkbox price
			jPrice = jForm.find(checkboxPriceSel);
			if (!(jPrice.data('price') > 0)) {
				jPrice.data('price', getPriceAmount(jPrice));
			}
			// get item id
			var itemId = jForm.find(idSel).eq(0).val();

			// each SELECT
			jForm.find(optionsSel).each(function(){
				// get name
				var name = $(this).attr('name');
				// get cookie value
				var cookieValue = getCookieValue(dataArr, itemId, name);
				// set value
				if (cookieValue !== null) {
					//$(this).val(unescape(cookieValue).replace('{plus}', '+'));
					$(this).val(cookieValue.replace('{plus}', '+'));
				}
				// define change()
				$(this).change(function(evt){
					// update item price
					updatePrice(jForm);
					// update cookie
					var value = $(this).val();
					formValueCookieUpdate(itemId, name, value);
				}); 
			});

			// each checkbox
			jForm.find(checkboxSel).each(function(){
				// get name
				var name = $(this).attr('name');
				// get cookie value
				var cookieValue = getCookieValue(dataArr, itemId, name);
				// set value
				if (cookieValue !== null) {
					if (cookieValue == '1') {
						$(this).attr('checked', 'checked');
					} else {
						$(this).removeAttr('checked');
					}
				}
				// define change()
				$(this).click(function(evt){
					// update item price
					updatePrice(jForm);
					// update cookie
					var value = ($(this).is(':checked')) ? '1' : '0';
					formValueCookieUpdate(itemId, name, value);
				}); 
			});

		}); // end each form
		// ----------------------------------------------------------------

		// initialize display prices by triggering checkbox click and SELECT change
		//$(formSel).find(checkboxSel).trigger('click');
		//$(formSel).find(optionsSel).trigger('change');

		// initialize display prices 
		$(formSel).each(function(){
			updatePrice($(this));
		});

	}; // end updateprice

	$(function(){ // document ready

		// tabs
		$('.tabs').tabs();
	
		// image rollovers
		$('.addtocartImg').rollover({'overAttr':'rel'});
	
		// gallery viewer
		$('.galleryviewer').galleryviewer({
			'changeEvent'	: 'mouseover'
		})

		$.collectorateUpdatePrice();

		// notify-me page, name in query string
		// insert product name into page
		do { // control
			var idx = document.URL.indexOf('?');
			if (idx == -1) { break; }
			var name = document.URL.substring(idx + 1);
			if (!(name.length > 0)) { break; }
			name = unescape(name.replace(/\+/g, ' '));
			$('.notify-when-available-form-page form #product-name').val(name);
		} while(0); // control

	}); // end ready

})(jQuery);

		/*$.collectorateUpdatePrice = function (jForm) {
			// get price object
			var jPrice = jForm.find(priceSel);
			// get base item price
			var price = jPrice.data('price');
			// get price differential total
			// start with checkbox price
			var checkboxTotal =		jForm.find(checkboxSel).is(':checked')
									? jForm.find(checkboxPriceSel).data('price')
									: 0;
			// add total options price
			var diffOption = 0;
			jForm.find(optionsSel).each(function(){
				var diff = $(this).val();
				diff = diff.match(/\((.*)\)/);
				diff = diff ? parseFloat(diff[1]) : 0;																 
				diffOption = diffOption + diff;
			});
			// set price
			jPrice.text(formatPrice((price * 1) + (checkboxTotal * 1) + (diffOption * 1)));
		};*/


	/*$.collectorateUpdatePrice = function (jForm, priceSel, checkboxSel, checkboxPriceSel, optionsSel) {
		// get price object
		var jPrice = jForm.find(priceSel);
		// get base item price
		var price = jPrice.data('price');
		// get price differential total
		// start with checkbox price
		var checkboxTotal =		jForm.find(checkboxSel).is(':checked')
								? jForm.find(checkboxPriceSel).data('price')
								: 0;
		// add total options price
		var diffOption = 0;
		jForm.find(optionsSel).each(function(){
			var diff = $(this).val();
			diff = diff.match(/\((.*)\)/);
			diff = diff ? parseFloat(diff[1]) : 0;																 
			diffOption = diffOption + diff;
		});
		// set price
		jPrice.text(formatPrice((price * 1) + (checkboxTotal * 1) + (diffOption * 1)));
	};*/


