/**
* @version $Id: store.js 55828 2011-12-27 19:01:04Z kt $ 
*
* Divinity: common store\fronend JS functionality: 
* - divinity.stock_level_images: stock-level image overlays 
* - divinity.box: inline-popup commands (divinity.box.open() and divinity.box.close())
* - divinity.review_votes: item reviews voting
* - divinity.failed_images: reloading failed item/category images
* - divinity.cart: shopping cart popup window functionality
* - item tabs
* - divinity.states: ajax states handler
* checkout guest register form
*
* Common 3rd-party stuff:
* - parse_url(),
* - css_browser_selector(),
* - jQuery.toJSON(),
* - jQuery.fn.modal()
*
*/
var TC = TC || {};
var divinity = divinity || {};

///////////////////////////////////////////////////////////////////////////////

/**
* Inline boxes and pop-ups
*/
divinity.box = {

	/**
	* Reference to the currently opened box
	* @access private
	*/	
	"_instance" : null,

	/**
	* Default spinner (it is used when no "loading" HTML is provided)
	* @access public
	*/	
	"_spinner" : '<div class="store-box-spinner"><\/div>',

	/**
	* Default error message (it is used when no error message is provided)
	* @access public
	*/
	"_error" : 'Sorry, this operation can not currently be completed. Please try again later.',
	
	/**
	* Cache for ajax responces
	* @access private
	*/
	"_ajax" : {},
	
	/**
	* Open up a box
	*
	* @param String html
	* @param Object o settings override
	*/
	"open" : function(html, o) {

		// if there is no SimpleModal or jQuery we got nothing to do...
		//
		if (typeof jQuery.modal != 'function') {
			return false;
			}

		// the options
		//
		o = jQuery.extend(true, {
			
			// whether to wrap the HTML in the "box" wrapping (with title and stuff)
			//
			"wrap": true,
			
			// title for the box
			//
			"title": '',
			
			// settings for ajax requests
			//
			"ajax": false,
			
			// settings for SimpleModal
			//
			"modal": {
				"opacity": 50,
				"position": [50],
				"zIndex": 9997,
				"onShow": divinity.states
				},

			// whether to handle form submition via ajax automatically
			//
			"handle_submit": true
			}, o);

		// default ajax handlers
		//
		var ajax = {
			"success": function(h) {

				// nothing returned ?
				//
				if (!h) {
					divinity.box.error(false, o.title); 
					return;
					}

				// cache the result
				//
//				divinity.box._ajax[cache_id] = h;

				// check if the box is opened (the customer
				// might've lost his patience and closed
				// the box prematurely)
				//
				if (!divinity.box._instance) {
					return;
					}
				
				delete(o.ajax);
				divinity.box.open(h, o);
				},

			"error": function() {
				/* use default error message but the box title */
				divinity.box.error(false, o.title); 
				}
			}

		// ajax box ?
		//
		if (o.ajax) {
			
			// check the ajax options
			//
			o.ajax = jQuery.extend({
				"url": smarty_vars.relative_request_uri || '',
				"type": 'POST'
				}, ajax, o.ajax);

			// already cached ?
			//
			var cache_id = jQuery.toJSON(o);
			if (typeof divinity.box._ajax[cache_id] == 'string') {
				delete(o.ajax);
				divinity.box.open(divinity.box._ajax[cache_id], o);
				return;
				}

			// place the ajax call
			//
			jQuery.ajax(o.ajax);
			
			// show the spinner
			//
			divinity.box.loading(o.ajax.loading || false);
			return;
			}
		
		// wrap it ?
		//
		if (o.wrap) {
			html = '<div class="store-box">' + (
				jQuery.trim(o.title)
					? ('<h1 class="store-box-title">' + o.title + '<\/h1>')
					: ''
				) + '<div class="store-box-content">' + html + '<\/div><\/div>';
			}
		
		// fucking IE8
		//
		if (jQuery.browser.msie) {

			// First without innerShiv() because of javascript..
			//
			divinity.box.close();
			divinity.box._instance = jQuery.modal(html, o.modal);
			html = innerShiv(html, false);
			}
		
		// KT: simplemodal needs all the stuff in the dom of the HTML
		// chunk to be inserted in advance in order to correctly 
		// calculate the width/height and the position of the window
		//
		if (typeof html != 'object') {
			var domChunk = document.createElement('div');
			jQuery(domChunk).html(html);
			html = domChunk;
			}

                // set the html and call a customTrigger to apply all
                // the changes that are going to be made for this piece
                // of HTML
                //
                jQuery(document).trigger('ajaxBoxHTML', [html, o]);
		
		// show the box
		//
		divinity.box.close();		
		
		
		//divinity.box._instance = jQuery.modal(html, o.modal);
		//jQuery(document).trigger('ajaxBoxLoaded');
		
		setTimeout(function(){
			divinity.box._instance = jQuery.modal(html, o.modal);
			jQuery(document).trigger('ajaxBoxLoaded');
			
			// are the forms in the box ? if there are, ajaxify them
			//
			if (o.handle_submit) {
				jQuery('#simplemodal-container form').submit(function() {
	
					// make the ajax call
					//
					var t = jQuery(this), a = jQuery.extend({
						"type": 'POST',
						"data" : t.serialize(),
						"url": t.attr('action')
						}, ajax);
					jQuery.ajax(a);
					
					// show the spinner
					//
					divinity.box.loading();
					return false;
					});
				}
	
				jQuery('#simplemodal-container form input[type="submit"]').click(function() {
					jQuery(this.form).append('<input type="hidden" value="' + this.value + '" name="' + this.name + '" \/>');
					return true;
				});
		}, 100);
		
		////preload states
		//divinity.box._instance.done(divinity.states);
		
		
		
		},
	
	/**
	* Shortcut function for showing a spinner (e.g. "Please wait while loading..." stuff)
	*
	* @param String html
	*/
	"loading": function(html) {
		divinity.box.close();

		if (html) {
			html = '<div class="store-box-loading">' + html + '<\/div>';
			}
		divinity.box._instance = jQuery.modal(html || divinity.box._spinner, {
			'closeHTML': ''
			});
		},

	/**
	* Shortcut function for showing an error message 
	*
	* @param String html
	* @param String title
	*/	
	"error": function(html, title) {
		divinity.box.close();
		html = html || divinity.box._error;
		divinity.box.open('<div class="error">' + html + '<\/div>', {
			'title': title || false
			});
		},
	
	/**
	* Close an opened box
	*/
	"close" : function() {
		if (divinity.box._instance && typeof divinity.box._instance.close == 'function') {
			divinity.box._instance.close();
			}
		}	
	}

/**
* All a.box-ajax links will be handled as ajax box popups
*/
jQuery('a.box-ajax').live('click', function() {
	divinity.box.open('', {
		'title': this.title || jQuery(this).text(), 
		'ajax': {'url': this.href}
		});
	return false;
	});

///////////////////////////////////////////////////////////////////////////////

/**
* Find the links which add items to cart
*/
function ajax_cart_find_links() {
	return jQuery('a').filter(function() {
		return this.href.indexOf('page=item') > -1 
			&& this.href.indexOf('action=cart') > -1  
			&& !this.hash;
		});
	}

/**
* Find the forms which add items to cart
*/
function ajax_cart_find_forms() {
	return jQuery('form').filter(function() {
		var d = jQuery(this).serialize();
		return d.indexOf('page=item') > -1 && d.indexOf('action=cart') > -1;
		});
	}

// ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 

// Shopping Bag Custom Events

// ajaxCartViewInit
// ajaxCartViewStart
// ajaxCartViewSuccess
// ajaxCartViewExecute
// ajaxCartViewAfter
// ajaxCartClose
// ajaxCartAddInit
// ajaxCartAddStart
// ajaxCartAddSuccess
// ajaxCartAddExecute
// ajaxCartAddAfter


/**
* Default cart adapter, operates with divinity.box
*/
function ajax_cart_box() {

	/**
	* Find the elements to which to attach the cart; these are usually A elements
	*/
	this.beacons = function() {
		return jQuery('a').filter(function() {
			return this.href.indexOf('page=cart') > -1 && !this.hash;
			});
		}

	/**
	* Hide the cart
	*/
	this.hide = function(a, operation) {
		divinity.box.close();
		}
	
	/**
	* Show the cart
	*/
	this.show = function(html, a, operation) {
		divinity.box.open(html, {
			'title': jQuery(a).attr('title') || jQuery(a).text()
			});
		}
	
	/**
	* Handler to executed before placing the ajax call
	*/
	this.before_ajax = function(a, operation) {
		var msg = {
			"add": "Adding to cart...",	
			"view": "Loading cart..."
			};
		divinity.box.loading(msg[operation]);
		return true;
		}

	/**
	* Handler to executed before showing the cart
	*/			
	this.before_show = function(a, operation) {
		divinity.box.close();
		}

	/**
	* Find the links which add items to cart
	*/
	this.links = ajax_cart_find_links;

	/**
	* Find the forms which add items to cart
	*/
	this.forms = ajax_cart_find_forms;
	}

// ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 

/**
* The AJAX shopping cart settings and common routines
*/
divinity.cart = {
		
	/**
	* Cart adapter, where all the specific behaviour is stored
	*/
	"adapter": new ajax_cart_box(),

	// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
	
	/**
	* View Cart
	*/
	'view': function() {
		
		var adapter = divinity.cart.adapter, a = jQuery(this);

		// jQuery event "ajaxCartViewInit"
		//
		a.trigger('ajaxCartViewInit', adapter);

		// "Before View Cart" event
		//
		if (typeof adapter.before_ajax == 'function') {
			if (!adapter.before_ajax(a, 'view')) {       
				return false;
				}
			}

		// jQuery event "ajaxCartViewStart"
		//
		a.trigger('ajaxCartViewStart', adapter);
		
		// place the ajax call
		//
		jQuery.ajax({
			"adapter": adapter, // KT: to make it available in the ajax object, e.g. this.adapter
			"url": smarty_vars.rel_html_url + '?page=cart',
			"type": 'GET',
			"dataType": 'html',
			"error": function() {
				
				// if there is an error, hide the cart container
				// and follow the cart link (e.g. change the page)
				//
				if (typeof adapter.hide == 'function') {
					adapter.hide(a, 'error.show');
					}
				document.location.href = this.url;
				},
			"success": function(o) {

				// jQuery event "ajaxCartViewSuccess"
				//
				a.trigger('ajaxCartViewSuccess', this, o);

				if (typeof adapter.before_show == 'function') {
					adapter.before_show(a, 'view');
					}

				// jQuery event "ajaxCartViewExecute"
				//
				a.trigger('ajaxCartViewExecute', this, o);

				adapter.show(o, a, 'view');

				// jQuery event "ajaxCartViewAfter"
				//
				a.trigger('ajaxCartViewAfter', this);
				
				} 
			});

		// KT: very important in order to halt the link
		//
		return false;
		},

	/**
	* Close Cart
	*/
	'close': function() {
		var adapter = divinity.cart.adapter, a = adapter.beacons().filter(function(i) {
			return !i;
			});

		// jQuery event "ajaxCartClose"
		//
		a.trigger('ajaxCartClose', adapter);

		if (typeof adapter.hide == 'function') {
			adapter.hide(a, 'close');
			}		
		},

	/**
	* Add to Cart
	*/
	'add': function(skus) {
		var t = this, adapter = divinity.cart.adapter, a = adapter.beacons().filter(function(i) {
			return !i;
			});

		// jQuery event "ajaxCartAddInit"
		//
		a.trigger('ajaxCartAddInit', adapter);

		// "Before Add to Cart" event
		//
		if (typeof adapter.before_ajax == 'function') {
                        if (!adapter.before_ajax(a, 'add')) {       
                                return false;
                                }
			}

		// jQuery event "ajaxCartAddStart"
		//
		a.trigger('ajaxCartAddStart', adapter);

		// prepare the ajax call
		//		
		var ajax = {
			"adapter": adapter, // KT: to make it available in the ajax object, e.g. this.adapter
			"url": smarty_vars.rel_html_url + '?page=item&action=cart',
			"type": 'POST',
			"dataType": 'html',
			"error": function() {

				// if there is an error, hide the cart container
				// and follow the cart link (e.g. change the page)
				//
				if (typeof adapter.hide == 'function') {
					adapter.hide(a, 'error.add');
					}
				document.location.href = this.url;
				},
			"success": function(o) {

				// jQuery event "ajaxCartAddSuccess"
				//
				a.trigger('ajaxCartAddSuccess', this, o);

				if (typeof adapter.before_show == 'function') {
					adapter.before_show(a, 'add');
					}

				// jQuery event "ajaxCartAddExecute"
				//
				a.trigger('ajaxCartAddExecute', this, o);

				adapter.show(o, a, 'add');
				
				// jQuery event "ajaxCartAddAfter"
				//
				a.trigger('ajaxCartAddAfter', this);
				} 
			};

		// the operation might be triggered not just by a link,
		// but also by a form or if called the form directly
		//
		switch(true) {
			
			// Link
			//
			case (this.tagName == 'A'):
				ajax.url = t.pathname + t.search;
				ajax.data = (parse_url(t.href)).params;	
				break;
			
			// Form
			//
			case (this.tagName == 'FORM'):
				ajax.data = jQuery(this).serialize();
				break;
			
			// direct call
			//
			case (this == window):
				ajax.data = skus;
				ajax.url += '&' + skus;
				break;
			}

		jQuery.ajax(ajax);

		// KT: very important in order to halt the link
		//
		return false;
		}

	} 

// ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 

/**
* Basic cart adapter, operates with all Divinity themes and DHTML panels
*/
function ajax_cart_basic() {

	/**
	* Initialize: check if the DHTML container exists
	*/
	function c(a) {
		var vc = jQuery('#shopping-cart-container');
		if (vc.length == 0) {
			a.before(
'<div id="shopping-cart-container" style="position:absolute;display:none;"><\/div>'
				);
			return c(a);
			}
		return vc;
		}

	/**
	* Find the elements to which to attach the cart; these are usually A elements
	*/
	this.beacons = function() {
		var found = false;
		return jQuery('a').filter(function() {
			if (found) return false;
			if (this.href.indexOf('page=cart') > -1 && !this.hash) {
				found = true;
				return true;
				}
			});
		}

	var ajaxClass = 'shopping-cart-ajax';
	
	/**
	* Hide the cart
	*/
	this.hide = function(a, operation) {
		c(a).html('').hide();
		jQuery(a).removeClass(ajaxClass);
		}

	/**
	* Show the cart
	*/		
	this.show = function(html, a, operation) {
		
		c(a).html(html);
		if (jQuery.browser.msie) {
			c(a).html(innerShiv(html));
			}
		
		// there is at least one form in the "View Cart"
		//
		var adapter = this;
		c(a).find('form').submit(function() {

			// "Before View Cart" event
			//
			if (!adapter.before_ajax(a, 'submit')) {
				return false;
				}

			// make the ajax call
			//
			var t = jQuery(this), ajax = {
				"success": function(o) {
					
					if (typeof adapter.before_show == 'function') {
						adapter.before_show(a);
						}

					adapter.show(o, a);					
					},
				"type": 'POST',
				"data" : t.serialize(),
				"url": t.attr('action')
				};
				
			jQuery.ajax(ajax);
			return false;
			});
		c(a).find('form input[type="submit"]').click(function() {
			jQuery(this.form).append(
				'<input type="hidden" value="' 
					+ this.value 
					+ '" name="' 
					+ this.name + '" \/>');
			return true;
			});
		}

	/**
	* Handler to executed before placing the ajax call
	*/
	this.before_ajax = function(a, operation) {

		is_form = (operation == 'submit' || operation == 'add');

		// second click on the link, close it
		//
		if (!is_form && jQuery('.' + ajaxClass).length) {
			jQuery('.' + ajaxClass).removeClass(ajaxClass);
			divinity.cart.close();
			return false;
			}

		// set the flag up that we are going to business
		//
		if (!is_form){
			a.addClass(ajaxClass);
			} else {
			jQuery('html,body').animate({"scrollTop": 0}, 'fast');	
			}
		
		// show the spinner
		//
		c(a).show();
		if (is_form && operation != 'add') {
			c(a).addClass('submitting');
			}else {
			c(a).html('').addClass('loading');
			}
		return true;
		}

	/**
	* Handler to executed before showing the cart
	*/		
	this.before_show = function(a, operation) {
		c(a).removeClass('loading').removeClass('submitting')
			.animate({"height": '+=320'}, 'fast', "linear", function(){ 
				c(a).css('height', 'auto');
				});
		}

	/**
	* Find the links which add items to cart
	*/
	this.links = ajax_cart_find_links;

	/**
	* Find the forms which add items to cart
	*/
	this.forms = ajax_cart_find_forms;
	}
	
divinity.cart.adapter = new ajax_cart_basic();

// ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 

/**
* The AJAX shopping cart handlers
*/
if (smarty_vars.cart_behavior == 'ajax') jQuery(document).ready(function() {
	
	// attach the "View Cart" handler
	//
	(divinity.cart.adapter.beacons()).click(divinity.cart.view);
	
	// attach the "Buy" handlers
	//		
	(divinity.cart.adapter.links())
		.click(divinity.cart.add);
	(divinity.cart.adapter.forms())
		.submit(divinity.cart.add);
	});

///////////////////////////////////////////////////////////////////////////////

/**
* Multiple Parent/Child selectors
*/
jQuery(document).ready(function () {
	var item_attributes = jQuery('form[name^="thumb-form-"]').find('select.item-attribute'),
	attributes = {}, lasts = {}, id, ppid, element, child_id, form, attributes_length;
	jQuery('form[name^="thumb-form-"] button:submit').live('click', function () {
		if (jQuery(this).is('.disabled')) {
			return false;
		}
	});

	if (item_attributes.length) {
		attributes_length = function (o) {
			var i = 0, key;
			if (typeof Object.keys == 'function') {
				return Object.keys(o).length;
			} else {
				for (key in o) {
					i++;
				}
				return i;
			}
		}

		for (id in mpd) {
			form = jQuery('form[name="thumb-form-' + id + '"]');
			lasts[id] = {};

			for (ppid in mpd[id].selectable_columns) {
				mpd[id]['ppid'] = ppid;
			}
			if (!attributes.hasOwnProperty(mpd[id]['ppid'])) {
				attributes[mpd[id]['ppid']] = mpd[id].selectable_columns[mpd[id]['ppid']];
			}
			if (mpd[id].inventory_control == 'in_stock_email' && attributes_length(attributes[mpd[id]['ppid']]) == 1) {
				element = form.find('select.item-attribute')[0];
				for (child_id in mpd[id].parent_data) {
					if (parseInt(mpd[id].parent_data[child_id].store_quantity) == 0) {
						form.find('select[name="' + element.name + '"] option[value="'
							+ mpd[id].parent_data[child_id][element.name] + '"]').addClass('disabled');
					}
				}
			}
		}

		jQuery('body').delegate(
			'form[name^="thumb-form-"] select.item-attribute',
			'change',
			function () {
				var radio = this,
					f = jQuery(this).closest('form'),
					item_id = f.attr('name').substring(11),
					attribute = jQuery(this).attr('name'),
					value = this.value,
					selectable_columns = [],
					selected_count, i;

				if (value) {
					f.find('select.item-attribute').each(function () {
						selectable_columns.push(this.name);
					});

					f.find('select[name!="' + attribute + '"] option').removeAttr('disabled').removeClass('disabled');
					f.find('select[name!="' + attribute + '"] option[value!=""]').attr('disabled', 'disabled');
				}

				// Trigger custom event
				//
				jQuery(document).trigger('parentChildChangeAttribute', [this, item_id]);

				if (!value) {
					return;
				}

				// Loop over the child items
				//
				for (child_id in mpd[item_id]['parent_data']) {

					// If value of changed attribute matches...
					//
					if (mpd[item_id]['parent_data'][child_id][attribute] === value) {

						// Loop over attributes
						//
						for (i = 0; i < selectable_columns.length; i++) {
							if (selectable_columns[i] != attribute) {

								// Loop over values of current attribute
								//
								f.find('select[name="'
									+ selectable_columns[i] + '"] option'
								).each(function () {

									// If there is a match, remove disabled attribute
									// from this attribute value
									//
									if (jQuery(this).val() === mpd[item_id]['parent_data'][child_id][selectable_columns[i]]) {
										if (parseInt(mpd[item_id].parent_data[child_id].store_quantity) === 0) {
											if (mpd[item_id].inventory_control == 'in_stock_email') {
												lasts[item_id] = lasts[item_id] || {};
												jQuery(this).removeAttr('disabled').addClass('disabled');
											}
										} else {
											jQuery(this).removeAttr('disabled');
										}
									}
								});
							}
						}
					}
				}

				// Count checked attributes
				//
				selected_count = f.find('select.item-attribute[value!=""]').size();

				// If all attributes are checked,
				// try to apply correct data(sku, store_price, etc..)
				//
				if (selected_count === selectable_columns.length) {

					// Loop over child items
					//
					itemsloop:
					for (child_id in mpd[item_id]['parent_data']) {

						// Loop over attributes
						//
						for (i = 0; i < selectable_columns.length; i++) {

							// If current attribute of current child item
							// is different from selected, go to next item...
							//
							if (
								mpd[item_id]['parent_data'][child_id][selectable_columns[i]] !== f.find('select[name="'
									+ selectable_columns[i] + '"]'
								).val()
							) {
								continue itemsloop;
							}
						}

						// In stock email?
						//
						if (jQuery(this).find('option:selected').is('.disabled')) {

							// Change selected attribute value to previous
							//
							if (lasts[item_id].hasOwnProperty(attribute)) {
								jQuery(this).find('option[value="' + lasts[item_id][attribute] + '"]').attr('selected', 'selected');
							} else {
								jQuery(this).find('option[value=""]').attr('selected', 'selected');
							}

							// Show in stock email popup
							//
							jQuery.ajax({
								url: smarty_vars.rel_html_url,
								data: 'page=item&action=in_stock_email_ajax_form&id=' + mpd[item_id].parent_data[child_id].sku,
								success: function (o) {
									var o = jQuery.parseJSON(o);
									divinity.box.open(
										o.content, {title: o.title}
									);
								}
							});
							return;
						}

						f.find('span.item-sku').text(
							mpd[item_id]['parent_data'][child_id].sku
						);
						f.find('input[name="id"]').val(
							mpd[item_id].parent_data[child_id].sku
						);

						f.find('input:submit, button:submit').unbind('mouseenter mouseleave');
						f.find('input:submit, button:submit').removeClass('disabled');

						// Custom event
						//
						jQuery(document).trigger('parentChildItemChanged', [radio, mpd[item_id].parent_data[child_id]]);
						break itemsloop;
					}
				}

				// Store last valid selection for each parent per attribute
				//
				if (mpd[item_id].inventory_control == 'in_stock_email') {
					lasts[item_id][attribute] = value;
				}
			}
		);

	} else {

		// IE 7/8 Hack!
		//
		if (
			navigator.userAgent.indexOf('MSIE 7') > -1
			|| navigator.userAgent.indexOf('MSIE 8') > -1
		) {
			jQuery('form[name^="thumb-form-"] label').live('click', function () {
				jQuery(
					'form[name^="thumb-form-"] input#' + jQuery(this).attr('for')
				).attr('checked', 'checked').trigger('change');
			});
		}

		jQuery('form[name^="thumb-form-"] input:radio').live('change', function () {

			var radio = this,
				f = jQuery(this).closest('form'),
				item_id = f.attr('name').substring(11),
				attribute = jQuery(this).attr('name'),
				value = this.value,
				selectable_columns = [],
				selected_count,
				i;

			f.find('input:submit, button:submit').addClass('disabled');

			for (profile_id in mpd[item_id]['selectable_columns']) {
				for (col in mpd[item_id]['selectable_columns'][profile_id]) {
					selectable_columns.push(col);
				}
			}

			// reset the selected state
			//
			f.find('input:radio[name!="' + attribute + '"]').removeAttr('disabled');
			f.find('dd:not(#dd-attr-' + item_id + '-' + attribute + ') li').removeClass('disabled');
			f.find('dd li').removeClass('selected');

			// Present checked attribute value
			//
			f.find('dt#attr-'
				+ item_id + '-' + attribute + ' span.selected-value'
			).text(value);

			// Disable other attribute values
			//
			f.find('input:radio[name!="' + attribute + '"]').attr('disabled', 'disabled');
			f.find('dd:not(#dd-attr-' + item_id + '-' + attribute + ') li').addClass('disabled');

			// Trigger custom event
			//
			jQuery(document).trigger('parentChildChangeAttribute', [this, item_id]);

			// Loop over the child items
			//
			for (child_id in mpd[item_id]['parent_data']) {

				// If value of changed attribute matches...
				//
				if (mpd[item_id].parent_data[child_id][attribute] === value) {

					// Loop over attributes
					//
					for (i = 0; i < selectable_columns.length; i++) {
						if (selectable_columns[i] != attribute) {

							// Loop over values of current attribute
							//
							f.find('input:radio[name="'
								+ selectable_columns[i] + '"]'
							).each(function () {

								// If there is a match, remove disabled attribute
								// from this attribute value
								//
								if (
									jQuery(this).val() ===
									mpd[item_id]['parent_data'][child_id][selectable_columns[i]]
									&& mpd[item_id]['parent_data'][child_id]['store_quantity'] > 0
								) {
									jQuery(this).removeAttr('disabled').parent().removeClass('disabled');
								}
							});
						}
					}
				}
			}

			f.find('input:radio:checked:not(:disabled)').each(function () {
				jQuery(this).parent().addClass('selected');
			});

			// Count checked attributes
			//
			selected_count = f.find('input:radio:checked:not(:disabled)').size();

			// If all attributes are checked,
			// try to apply correct data(sku, store_price, etc..)
			//
			if (selected_count === selectable_columns.length) {

				// Loop over child items
				//
				itemsloop:
				for (child_id in mpd[item_id]['parent_data']) {

					// Loop over attributes
					//
					for (i = 0; i < selectable_columns.length; i++) {

						// If current attribute of current child item
						// is different from selected, go to next item...
						//
						if (
							encodeURIComponent(
								mpd[item_id]['parent_data'][child_id][selectable_columns[i]]
							) !== encodeURIComponent(
								f.find('input:radio[name="'
								+ selectable_columns[i] + '"]:checked'
							).val())
						) {
							continue itemsloop;
						}
					}
					f.find('input[name="id"]').val(
						mpd[item_id]['parent_data'][child_id]['sku']
					);
					jQuery(
						'article#thumb-' + item_id
						+ ' div.thumb-main ul li abbr[title="Store Price"] strong'
					).text(
						mpd[item_id]['parent_data'][child_id]['store_price']
					);
					f.find('input:submit, button:submit').unbind('mouseenter mouseleave');
					f.find('input:submit, button:submit').removeClass('disabled');

					// Custom event
					//
					jQuery(document).trigger('parentChildItemChanged', [radio, mpd[item_id]['parent_data'][child_id]]);
					break itemsloop;
				}
			}
		});

	}

	/*
	* Trigger custom event
	*
	* to bind a functionality to this custom event use:
	*
	* jQuery(document).bind('parentChildAfterInit', function () {...}); before jQuery(document).ready();
	*/
	//if (navigator.userAgent.indexOf('Chrome') > -1) {
	//	setTimeout(
			//function(){
				jQuery(document).trigger('parentChildAfterInit');
			//},
	//		500
	//	);
	//} else {
	//	jQuery(this).trigger('parentChildAfterInit');
	//}

});

///////////////////////////////////////////////////////////////////////////////

/**
* Add To List(Wishlist/Gift Registry)
*/
jQuery(document).ready(function () {
	var cache_html = '', a,
		add = function () {
			var group = jQuery('#groups').val() || jQuery('#wishlists-select').val()
			jQuery.ajax({
				url: smarty_vars.rel_html_url,
				type: 'POST',
				data: 'page=wishlists&action=add&id='
					+ window.wishlist_sku
					+ '&qty=' + window.wishlist_qty
					+ (typeof group == 'undefined' ? '' : '&group=' + group),
				dataType: 'html',
				success: function(msg) {
					divinity.box.open(msg, {title: window.wishlist_title});
				}
			});
			divinity.box.loading();
		};

	jQuery('a[href*="page=wishlists"]').filter(function () {
		return this.href.indexOf('action=update') > -1;
	}).click(function () {
		
		jQuery(location).attr(
			'href',
			smarty_vars.rel_html_url
			+ 'index.php?'
		);
	});

	jQuery('a[href*="page=wishlists"]').filter(function () {
		return this.href.indexOf('action=add') > -1;
	}).click(function () {
		
		var url = parse_url(jQuery(this).attr('href')); 
		if (jQuery(this).is('.disabled')) {
			return false;
		}
		if (jQuery(this).is('.add-parent-to-wishlist')){ 
			window.location = $(this).attr('href');
		} else { 
		var add_to_list = function (a) {
			var f , data;
			if (jQuery('form[name^="thumb-form-"]').length){
				f = jQuery('form[name^="thumb-form-"]');
			} else {
				f = jQuery('form[name="display"]');
			}
			
			divinity.box.close();
			if (smarty_vars.divinity.page == 'item' && smarty_vars.divinity.action == 'index') { 
				window.wishlist_sku = f.find('input[name="id[0]"]').val() || f.find('input[name="id"]').val();
				window.wishlist_qty = f.find('input[name="qty[0]"], select[name="qty[0]"]').val() || f.find('input[name="qty"], select[name="qty"]').val();
			} else {
				data = parse_url(jQuery(a).attr('href'));
				window.wishlist_sku = data.params.id;
				window.wishlist_qty = 1;
			}
			window.wishlist_title = a.title;

			// If there is no html, there is only one List..
			// Add item to the List
			//
			if (jQuery.trim(cache_html).length === 0) {
				return add();
			}
			divinity.box.open(cache_html, {title: a.title});
		};
		a = this;
		if (cache_html) {
			add_to_list(a);
		} else {
			var sku = '';
			
			if (smarty_vars.divinity.page == "item"){
				sku = smarty_vars.id;
			} else {
				sku = url.params.id;
			}  
			divinity.box.loading('Fetching your Lists...');
			jQuery.ajax({
				url: smarty_vars.rel_html_url,
				type: 'GET',
				data: 'page=registry&action=lists&sku='+sku,
				dataType: 'html',
				success: function (o) {
					cache_html = o;
					add_to_list(a);
					jQuery('a.not-logged-wishlist').attr(
						'href',
						jQuery('a.not-logged-wishlist').attr('href')
						+ '&return_url=' + smarty_vars.return_url
					);
				}
			});
			return false;
		}
		return false;
		}
	});

	jQuery('input.ajax-wishlist, button.ajax-wishlist').live('click', function () { 
		jQuery(document).trigger('beforeAddToWishlist', [a]);
		add();
		jQuery(document).trigger('afterAddToWishlist', [a]);
		return false;
	});
	
});

///////////////////////////////////////////////////////////////////////////////

/** 
* The item-tab handlers
*/
jQuery(document).ready(function() {

	// are there declared tabs ?
	//
	var d = jQuery('div.item-tab');
	if (d.length == 0) {
		return;
		}
		
	// create tabs navigation before the first tab
	//
	var n = jQuery(document.createElement("div")).attr('id', 'item-tabs-nav');
	jQuery(d.get(0)).before(n[0]);


	// sort the tabs
	//
	var t = [];
	d.each(function() {
		t.push((this.className.match(/item-tab-sort-(\d+)($|\s)/gi))[0]);
		});
	t.sort();
	for (var i in t) {
		jQuery('.' + t[i]).insertAfter(n);
		}
	d = jQuery('div.item-tab'); /* fetch them after the tabs are re-arranged */


	// create the heading -> tabs association, put the handlers
	//
	d.each(function(i) {

		var t = jQuery(this), h = t.find(' > h1, > h4'), z;
		
		h.find('a')
			
			/* know your tab by the rel->id association */
			.attr('rel', this.id)
			
			/* look for the ajax url in this.ajax */
			.each(function() {
				this.ajax = this.href;
				z = this.href = '#!' + this.rel;
				})
			
			/* attach the handler */
			.click(function() { 
				var id = this.rel;
				
				/* swap the nav area */
				jQuery('.item-tab-selected').removeClass('item-tab-selected');
				jQuery(this).parent().addClass('item-tab-selected');
				
				/* swap the tabs */
				d.hide();
				var s = jQuery('#' + id);
				s.show();
				
				if (this.ajax) {
					jQuery.ajax({
						"url": this.ajax,
						"method": "POST",
						"success": function(o) {
							s.find('.item-tab-spinner').fadeOut('slow').after(o).remove();
							},
						"error": function() {
							this.success('Couldn\'t load this tab. We\'ll try to fix this as soon as possible.');
							}
						});
					this.ajax = ''; 
					}

				this.blur();
				return true;
				});

		/* move it to the navigation */
		h.addClass('item-tab-nav').appendTo(n[0]);
		
		/* style the tab itself, show the first tab */	
		t.addClass('item-tab-loaded');
		
		/* which tab is picked: something from the url or just the first one? */
		if ((document.location.hash == z) || (!document.location.hash && i == 0)) {
			t.show();
			h.find('a').click();
			} else {
			t.hide();
			}
		});
	
	// check if there is a tab selected - if not hit the first one
	//
	var h1 = d.find(' > h1, > h4');
	if(h1.filter('.item-tab-selected').length == 0) {
		h1.find(' a:eq(0)').click();
		}

	
	// attach the link handlers for switching the tabs, e.g. <a href="#!more">more</a>
	//
	jQuery('a').filter(function() {
			return (typeof this.hash == 'string') 
				&& this.hash.length > 1
				&& jQuery(this).parents('h1.item-tab-nav').length == 0;
			})
		.click(function() {
			var c1 = jQuery('h1.item-tab-nav a[href="#!' + this.hash.substr(1) + '"]');
			if (c1.length == 1) {
				c1.click().focus();

				jQuery('html,body').animate(
					{"scrollTop": (c1.offset().top - 20)}, /* 20px buffer for the viewport */
					500); 
				}
			});
	}
);

///////////////////////////////////////////////////////////////////////////////

/** 
* Apply stock-level image overlays 
*/
divinity.stock_level_enabled = false;
divinity.stock_level_images = function() {

	if (!divinity.stock_level_enabled) {
		return false;
		}

	var skus = [];

	jQuery('a > img').filter(
		function() {
			/* use only item images */
			return (typeof this.src == 'string' 
				&& this.src.indexOf('mas_assets/image_cache/') != -1);
					// ^
					// the stupid typeof this.src is an IE hack 
			}
		).each(
		function() {

			/* extract the SKU */
			var href = this.parentNode.href, sku = href.match(/\/item\/([^\/]+)\//i);

			/* pretty URLs */
			if (sku != null && sku.length == 2) {
				jQuery(this.parentNode).addClass(sku[1]);
				skus.push(sku[1]);
				return true;
				}
			/* regular URLs */
			if (href.search(/page=item/i) != -1) {
				sku = href.match(/id=([^&]+)($|&)/i);
				jQuery(this.parentNode).addClass(sku[1]);
				skus.push(sku[1]);
				return true;
				}
			}
		);

	if (skus.length == 0) {
		return;
		}

	jQuery.getJSON(
		smarty_vars.rel_html_url 
			+ 'index.php?page=item_ajax&action=stock_levels&id=' 
			+ encodeURIComponent(jQuery.toJSON(skus)), 
		function(data) {
			jQuery.each(data, 
				function(sku, level) {
					jQuery('a.' + sku)
						.removeClass(sku)
						.addClass('stock-level-' + level);
				})
		});
	}
jQuery(document).ready(
	divinity.stock_level_images
	);

///////////////////////////////////////////////////////////////////////////////

/** 
* Item reviews voting
*/
divinity.review_votes = function() {
	jQuery('a.review-vote').live('click', function() {
		
		if (typeof this.rel != 'string') {
			return false;
			}
		
		// fetch the sku and the review_id
		//
		var review_id = this.rel.substr(1+this.rel.lastIndexOf(':')), 
		sku = this.rel.substring(0, this.rel.lastIndexOf(':'));
		
		// find the place where to report the output, show the spinner, etc.
		//
		var p = jQuery(this).parent(),
		b = 'review-vote-' + review_id, 
		a = p.find('a.review-vote').filter('[rel="' + this.rel + '"]')
		c = p.find('.review-votes');
		if (p.find('.' + b).length == 0) {
			a.filter(':last').after('<span class="' + b + '"><\/span>');
			}
		b = p.find('.' + b);
		
		// place the vote via ajax
		//
		jQuery.ajax({
			'url': smarty_vars.rel_html_url,
			'type': 'POST',
			'data': {
				'page': 'review',
				'action': 'vote',
				'id': sku,
				'review': review_id,
				'vote': jQuery(this).hasClass('review-vote-yes')
					? '1'
					: '0'
				},
			'success': function(o) {
				c.hide();
				a.hide();
				b.addClass('review-vote-response').html(o);
				setTimeout(function(){
					b.fadeOut('slow', function() {
						jQuery(this).html('').show();
						});
					}, 4000);
				},
			'error': function() {
				this.success('<div class="error">' + divinity.box._error + '<\/div>');
					// ^
					// KT: re-use the error message for the boxes
				c.show();
				a.show();

				}
			});
		
		// show the spinner
		//
		b.removeClass('review-vote-response')
			.html('<span class="review-vote-spinner"><\/span>');
		
		return false;
		});
	}
jQuery(document).ready(
	divinity.review_votes
	);

///////////////////////////////////////////////////////////////////////////////

/** 
* Check if there are images that failed to load
*/
divinity.failed_images = function() {

	jQuery(document.images).filter(
		function() {

			/* use only item images */
			return (typeof this.src == 'string' 
				&& this.src.indexOf('mas_assets/image_cache/') != -1
					// ^
					// the stupid typeof this.src is an IE hack 

				&& (this.naturalHeight == 0 
					|| this.naturalWidth == 0 
					|| this.clientHeight == 0 
					|| this.clientWidth == 0)
						// ^
						// empty images: probably not loaded ? */
				);
			}
		).each(
		function() {

			var i = new Image(), t = this;			
			i.onload = function() {
				t.src = this.src;
				}
			i.src = t.src + '?' + (10 * Math.random());
			}
		);
	}

jQuery(document).ready(
	divinity.failed_images
	);

///////////////////////////////////////////////////////////////////////////////
/**
* Form Toggle for Checkout Auth Page
*/
if (smarty_vars.divinity.page == 'checkout') {

	var new_form = jQuery('#auth section#new fieldset:eq(0)');
	var guest_form = jQuery('#auth section#guest fieldset:eq(0)');

	jQuery(document).ready(function() {

		jQuery('#auth section#new button').click(function() {
			if (new_form.css('display') == 'none') {
				guest_form.slideUp();
				new_form.slideDown();
				return false;
			}
			return true;
		});
		jQuery('#auth section#guest button').click(function() {
			if (guest_form.css('display') == 'none') {
				guest_form.slideDown();
				new_form.slideUp();
				return false;
			}
			return true;
		});

		// Hint: Default action
		switch (smarty_vars.divinity.action) {
			default:
				guest_form.slideUp();
				break;			
			case 'start_guest':
				new_form.slideUp();
				break;
		}
		
	});	
}

///////////////////////////////////////////////////////////////////////////////

/**
 * Attach the states ajax handlers
 * 
 * How it works: you got to mark the country SELECTs with the "ajax-states" CSS 
 * class -- this means that they have the AJAX states-loading attached to them; 
 * in addition to that you got to have 2 inputs for the data: one text input for
 * the "state" (in text form) and one select for the "state_id" (where it is 
 * selected from a list of options); those 2 inputs must have a CSS class that 
 * follows this format: "ajax-states-" + the name or the id of the country 
 * select, e.g. "ajax-states-country_id" for "country_id" or 
 * "ajax-states-cc_country_id" for "cc_country_id".  
 */
divinity.states = function() {

	// are there country selects that need ajax states ?
	//
	var c = jQuery('select.ajax-states');
	if (!c.length) return false;

	// the handler
	//
	var ajax_states = function() {

		var s = jQuery(this.form).find(
			'.ajax-states-' + this.id  + ', .ajax-states-' + this.name 
		), success = function (o) {

			// if there is any content returned, then it has to be the
			//  options for the select; otherwise if it is empty then
			//  we got to show the text input
			//
			var a = s.filter('input'), b = s.filter('select');
			if (jQuery.trim(o)) {
				a = s.filter('select');
                                a.html(o);
				b = s.filter('input');
			}

			a.removeAttr('disabled').css('display', '');
			b.css('display', 'none');

			jQuery(country_select).trigger('ajaxStatesSuccess', a.get(0));
			// ^
			// execute a custom event on the country select

		}, complete = function () {
			jQuery(country_select).trigger('ajaxStatesComplete');
			// ^
			// execute a custom event on the country select

			jQuery('.ajax-states-loading').removeClass('ajax-states-loading');
			jQuery('.ajax-states-spinner').fadeOut('slow', function() {
				jQuery(this).remove();
			});
		};
		if (!s.length) return false;

	 	// show the spinner, disable the inputs
	 	//
	 	jQuery(s.parent().get(0)).addClass('ajax-states-loading').append(
	 		'<span class=\"ajax-states-spinner\">&nbsp;<\/span>'
	 		);
	 	s.attr('disabled', 'disabled');

		// the select is also the state_id no matter what is its
		// name ("state_id" or "cc_state_id"), while the text 
		// input is always the text state (named "state" or "cc_state")
		//
		var data = {
			'id': jQuery(this).val(),
			'state_id': s.filter('select').val(),
			'state': s.filter('input').val(),
			'page': 'states' 
			};
			
		var country_select = this;
		jQuery.ajax({
			"type": 'GET',
			"url": smarty_vars.rel_html_url + '?' + Math.random(),
			"dataType": 'html',
			"data": data,
			"success": success,
			"complete": complete
		});
	}

	// attach the handler
	//  		
	c.unbind('change')
		.bind('change', ajax_states)
		.each(function() {
			jQuery(this).triggerHandler('change');
				// ^
				// trigger the event for loading the default
				// values after the document is loaded
		});
 
	}

jQuery(document).ready(
	divinity.states
	);

///////////////////////////////////////////////////////////////////////////////

/** Handling shipping methods in My Account */
divinity.load_shipping_methods = function() {
	
	setTimeout(function() { 
		
		function _update_shipping_methods() 
		{
			var country_id = jQuery('[name="country_id"]').val();
			var state_id = jQuery('select[name="state_id"]').val() && !jQuery('select[name="state_id"]').attr("disabled") ? jQuery('input[name="state_id"]').val() : 0;
			if (!country_id)
			{
				return false;
			}
			
			var shipping_method_id = jQuery('input[name="method_id"]').val();
			
			jQuery.ajax({
				"url": smarty_vars.rel_html_url 
				+ '?type=ajax&page=shipping_smarty&action=get_all_available_methods&country_id=' 
				+ country_id + '&state_id=' 
				+ state_id + '&shipping_method_id='
				+ shipping_method_id,
				"success": function(data) {jQuery("#shipping_methods").html(data);}
			});
		}
		
		_update_shipping_methods();
		jQuery('.shipping_observable').change(_update_shipping_methods);
		
	}, 300);
	
	
}

/** Handling wallet type swap in My Account */
divinity.wallet_type_swap = function() {
	
	/**
	*/
	function wallet_type_swap(slct) 
	{

		var slctr = '.wallet_type_' + jQuery(slct).val();
		if (!slctr.length) {
			return false;
			}

		// reset all: hide and disable everything
		//
		jQuery('.wallet_type').css('display', 'none');
		jQuery('.wallet_type input,.wallet_type select,.wallet_type textarea')
			.attr('disabled', 'disabled');

		// show only the selected, enable it, and make it "last" (so if
		// they is an input-name clash, the selected payment type will be
		// the last one, and its values will have the "upper" hand)
		//
		jQuery(slctr).css('display', 'block');
		jQuery(slctr + ' *').find('input,select,textarea').removeAttr('disabled');
		jQuery(slctr)[0].parentNode.appendChild(
			jQuery(slctr)[0]
			);
	}

	/**
	*/
	setTimeout(function() {
			wallet_type_swap(
				jQuery('#wallet_type').get(0)
				);
			}, 300);
	
	
}

/////////////////////////////////////////////////////////////////////////////
	
/**
* This function creates a new anchor element and uses location
* properties (inherent) to get the desired URL data. Some String
* operations are used (to normalize results across browsers).
*
* @link http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*/
function parse_url(url) {

    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

///////////////////////////////////////////////////////////////////////////////

/**
* jQuery JSON implementation: jQuery.toJSON() 
*/
(function ($) {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

	$.toJSON = function(v) {
		var f = isNaN(v) ? s[typeof v] : s['number'];
		if (f) return f(v);
	};

})(jQuery);


/**
* Divinity localStorage wrapper
*/
divinity.localStorage = (function () {
	var ls;
	try {
		localStorage.getItem();
		ls = localStorage;
	} catch (e) {
		return false;
	}
	if (!ls.getItem('public')) {
		ls.setItem('public', '{}')
	}
	if (!ls.getItem('private')) {
		ls.setItem('private', '{}')
	}
	return {
		setPrivate: function (key, value) {
			var private = jQuery.parseJSON(ls.getItem('private'));
			if (typeof value === object) {
				private[key] = jQuery.extend(private[key], value);
			} else {
				private[key] = value;
			}
			return ls.setItem('private', jQuery.toJSON(private));
		},
		setPublic: function (key, value) {
			var public = jQuery.parseJSON(ls.getItem('public'));
			if (typeof value === 'object') {
				public[key] = jQuery.extend(public[key], value);
			} else {
				public[key] = value;
			}
			return ls.setItem('public', jQuery.toJSON(public));
		},
		getPrivate: function (key) {
			var private = jQuery.parseJSON(ls.getItem('private'));
			return private[key];
		},
		getPublic: function (key) {
			var public = jQuery.parseJSON(ls.getItem('public'));
			return public[key];
		},
		clearPublic: function () {
			ls.setItem('public', '{}');
		},
		clearPrivate: function () {
			ls.setItem('private', '{}');
		},
		removePrivate: function (key) {
			var private = jQuery.parseJSON(ls.getItem('private'));
			delete private[key];
			return ls.setItem('private', jQuery.toJSON(private));
		},
		removePublic: function (key) {
			var public = jQuery.parseJSON(ls.getItem('public'));
			delete public[key];
			return ls.setItem('public', jQuery.toJSON(public));
		}
	};
})();

///////////////////////////////////////////////////////////////////////////////

/**
* If Google Analytics Tracking is enabled, and the site is using a shared SSL
* certificate (whatever.make-a-s-tore.com) we need to apply this fix in order
* to make GA work for that domain as well.
*/
if (typeof _gaq == 'object' && smarty_vars.secure_html_url.match(/make-a-store\.com/gi)) {

	jQuery(document).ready(function() {
		
		// first fix the links...
		//
		jQuery(document.links).filter(function() {
			return this.href.indexOf(smarty_vars.secure_html_url) != -1;
			}).each(function() {
			this.onclick='_gaq.push(\'_link\', this.href); return false;';
			});
		
		// ...then the forms
		//
		jQuery(document.forms).filter(function() {
			return jQuery(this).attr('action').indexOf(smarty_vars.secure_html_url) != -1;
			}).each(function() {
			this.onsubmit='_gaq.push(\'_linkByPost\', this);';
			});
		});
	}

///////////////////////////////////////////////////////////////////////////////

/*
* jCarousel Functionality
*/
jQuery(document).ready(function() {
	if (jQuery.fn.jcarousel) {
		jQuery('ul.jcarousel.horizontal').jcarousel({
			vertical: false,
			scroll: 4
		});
	}
});


//if (jQuery.browser.msie && parseInt($.browser.version) === 7) {
///////////////////////////////////////////////////////////////////////////////

/*
 * SimpleModal 1.4.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2010 Eric Martin (http://twitter.com/ericmmartin)
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: store.js 55828 2011-12-27 19:01:04Z kt $
 */
(function ($) {
	var ie6 = $.browser.msie && parseInt($.browser.version) === 6 && typeof window['XMLHttpRequest'] !== 'object',
		ie7 = $.browser.msie && parseInt($.browser.version) === 7,
		ieQuirks = null,
		w = [];

	/*
	 * Create and display a modal dialog.
	 *
	 * @param {string, object} data A string, jQuery object or DOM object
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.modal = function (data, options) {
		return $.modal.impl.init(data, options);
	};

	/*
	 * Close the modal dialog.
	 */
	$.modal.close = function () {
		$.modal.impl.close();
	};

	/*
	 * Set focus on first or last visible input in the modal dialog. To focus on the last
	 * element, call $.modal.focus('last'). If no input elements are found, focus is placed
	 * on the data wrapper element.
	 */
	$.modal.focus = function (pos) {
		$.modal.impl.focus(pos);
	};

	/*
	 * Determine and set the dimensions of the modal dialog container.
	 * setPosition() is called if the autoPosition option is true.
	 */
	$.modal.setContainerDimensions = function () {
		$.modal.impl.setContainerDimensions();
	};

	/*
	 * Re-position the modal dialog.
	 */
	$.modal.setPosition = function () {
		$.modal.impl.setPosition();
	};

	/*
	 * Update the modal dialog. If new dimensions are passed, they will be used to determine
	 * the dimensions of the container.
	 *
	 * setContainerDimensions() is called, which in turn calls setPosition(), if enabled.
	 * Lastly, focus() is called is the focus option is true.
	 */
	$.modal.update = function (height, width) {
		$.modal.impl.update(height, width);
	};

	/*
	 * Chained function to create a modal dialog.
	 *
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.fn.modal = function (options) {
		return $.modal.impl.init(this, options);
	};

	/*
	 * SimpleModal default options
	 *
	 * appendTo:		(String:'body') The jQuery selector to append the elements to. For .NET, use 'form'.
	 * focus:			(Boolean:true) Focus in the first visible, enabled element?
	 * opacity:			(Number:50) The opacity value for the overlay div, from 0 - 100
	 * overlayId:		(String:'simplemodal-overlay') The DOM element id for the overlay div
	 * overlayCss:		(Object:{}) The CSS styling for the overlay div
	 * containerId:		(String:'simplemodal-container') The DOM element id for the container div
	 * containerCss:	(Object:{}) The CSS styling for the container div
	 * dataId:			(String:'simplemodal-data') The DOM element id for the data div
	 * dataCss:			(Object:{}) The CSS styling for the data div
	 * minHeight:		(Number:null) The minimum height for the container
	 * minWidth:		(Number:null) The minimum width for the container
	 * maxHeight:		(Number:null) The maximum height for the container. If not specified, the window height is used.
	 * maxWidth:		(Number:null) The maximum width for the container. If not specified, the window width is used.
	 * autoResize:		(Boolean:false) Automatically resize the container if it exceeds the browser window dimensions?
	 * autoPosition:	(Boolean:true) Automatically position the container upon creation and on window resize?
	 * zIndex:			(Number: 1000) Starting z-index value
	 * close:			(Boolean:true) If true, closeHTML, escClose and overClose will be used if set.
	 							If false, none of them will be used.
	 * closeHTML:		(String:'<a class="modalCloseImg" title="Close"></a>') The HTML for the default close link.
								SimpleModal will automatically add the closeClass to this element.
	 * closeClass:		(String:'simplemodal-close') The CSS class used to bind to the close event
	 * escClose:		(Boolean:true) Allow Esc keypress to close the dialog?
	 * overlayClose:	(Boolean:false) Allow click on overlay to close the dialog?
	 * position:		(Array:null) Position of container [top, left]. Can be number of pixels or percentage
	 * persist:			(Boolean:false) Persist the data across modal calls? Only used for existing
								DOM elements. If true, the data will be maintained across modal calls, if false,
								the data will be reverted to its original state.
	 * modal:			(Boolean:true) User will be unable to interact with the page below the modal or tab away from the dialog.
								If false, the overlay, iframe, and certain events will be disabled allowing the user to interact
								with the page below the dialog.
	 * onOpen:			(Function:null) The callback function used in place of SimpleModal's open
	 * onShow:			(Function:null) The callback function used after the modal dialog has opened
	 * onClose:			(Function:null) The callback function used in place of SimpleModal's close
	 */
	$.modal.defaults = {
		appendTo: 'body',
		focus: true,
		opacity: 50,
		overlayId: 'simplemodal-overlay',
		overlayCss: {},
		containerId: 'simplemodal-container',
		containerCss: {},
		dataId: 'simplemodal-data',
		dataCss: {},
		minHeight: null,
		minWidth: null,
		maxHeight: null,
		maxWidth: null,
		autoResize: false,
		autoPosition: true,
		zIndex: 1000,
		close: true,
		closeHTML: '<a class="modalCloseImg" title="Close"></a>',
		closeClass: 'simplemodal-close',
		escClose: true,
		overlayClose: false,
		position: null,
		persist: false,
		modal: true,
		onOpen: null,
		onShow: null,
		onClose: null
	};

	/*
	 * Main modal object
	 * o = options
	 */
	$.modal.impl = {
		/*
		 * Contains the modal dialog elements and is the object passed
		 * back to the callback (onOpen, onShow, onClose) functions
		 */
		d: {},
		/*
		 * Initialize the modal dialog
		 */
		init: function (data, options) {
			var s = this;

			// don't allow multiple calls
			if (s.d.data) {
				return false;
			}

			// $.boxModel is undefined if checked earlier
			ieQuirks = $.browser.msie && !$.boxModel;

			// merge defaults and user options
			s.o = $.extend({}, $.modal.defaults, options);

			// keep track of z-index
			s.zIndex = s.o.zIndex;

			// set the onClose callback flag
			s.occb = false;

			// determine how to handle the data based on its type
			if (typeof data === 'object') {
				// convert DOM object to a jQuery object
				data = data instanceof jQuery ? data : $(data);
				s.d.placeholder = false;

				// if the object came from the DOM, keep track of its parent
				if (data.parent().parent().size() > 0) {
					data.before($('<span></span>')
						.attr('id', 'simplemodal-placeholder')
						.css({display: 'none'}));

					s.d.placeholder = true;
					s.display = data.css('display');

					// persist changes? if not, make a clone of the element
					if (!s.o.persist) {
						s.d.orig = data.clone(true);
					}
				}
			}
			else if (typeof data === 'string' || typeof data === 'number') {
				// just insert the data as innerHTML
				data = $('<div></div>').html(data);
			}
			else {
				// unsupported data type!
				alert('SimpleModal Error: Unsupported data type: ' + typeof data);
				return s;
			}

			// create the modal overlay, container and, if necessary, iframe
			s.create(data);
			data = null;

			// display the modal dialog
			s.open();

			// useful for adding events/manipulating data in the modal dialog
			if ($.isFunction(s.o.onShow)) {
				s.o.onShow.apply(s, [s.d]);
			}

			// don't break the chain =)
			return s;
		},
		/*
		 * Create and add the modal overlay and container to the page
		 */
		create: function (data) {
			var s = this;

			// get the window properties
			w = s.getDimensions();

			// add an iframe to prevent select options from bleeding through
			if (s.o.modal && ie6) {
				s.d.iframe = $('<iframe src="javascript:false;"></iframe>')
					.css($.extend(s.o.iframeCss, {
						display: 'none',
						opacity: 0,
						position: 'fixed',
						height: w[0],
						width: w[1],
						zIndex: s.o.zIndex,
						top: 0,
						left: 0
					}))
					.appendTo(s.o.appendTo);
			}

			// create the overlay
			s.d.overlay = $('<div></div>')
				.attr('id', s.o.overlayId)
				.addClass('simplemodal-overlay')
				.css($.extend(s.o.overlayCss, {
					display: 'none',
					opacity: s.o.opacity / 100,
					height: s.o.modal ? w[0] : 0,
					width: s.o.modal ? w[1] : 0,
					position: 'fixed',
					left: 0,
					top: 0,
					zIndex: s.o.zIndex + 1
				}))
				.appendTo(s.o.appendTo);

			// create the container
			s.d.container = $('<div></div>')
				.attr('id', s.o.containerId)
				.addClass('simplemodal-container')
				.css($.extend(s.o.containerCss, {
					display: 'none',
					position: 'fixed',
					zIndex: s.o.zIndex + 2
				}))
				.append(s.o.close && s.o.closeHTML
					? $(s.o.closeHTML).addClass(s.o.closeClass)
					: '')
				.appendTo(s.o.appendTo);

			s.d.wrap = $('<div></div>')
				.attr('tabIndex', -1)
				.addClass('simplemodal-wrap')
				.css({height: '100%', outline: 0, width: '100%'})
				.appendTo(s.d.container);

			// add styling and attributes to the data
			// append to body to get correct dimensions, then move to wrap
			s.d.data = data
				.attr('id', data.attr('id') || s.o.dataId)
				.addClass('simplemodal-data')
				.css($.extend(s.o.dataCss, {
						display: 'none'
				}))
				.appendTo('body');
			data = null;

			s.setContainerDimensions();
			s.d.data.appendTo(s.d.wrap);

			// fix issues with IE
			if (ie6 || ieQuirks) {
				s.fixIE();
			}
		},
		/*
		 * Bind events
		 */
		bindEvents: function () {
			var s = this;

			// bind the close event to any element with the closeClass class
			$('.' + s.o.closeClass).bind('click.simplemodal', function (e) {
				e.preventDefault();
				s.close();
			});

			// bind the overlay click to the close function, if enabled
			if (s.o.modal && s.o.close && s.o.overlayClose) {
				s.d.overlay.bind('click.simplemodal', function (e) {
					e.preventDefault();
					s.close();
				});
			}

			// bind keydown events
			$(document).bind('keydown.simplemodal', function (e) {
				if (s.o.modal && e.keyCode === 9) { // TAB
					s.watchTab(e);
				}
				else if ((s.o.close && s.o.escClose) && e.keyCode === 27) { // ESC
					e.preventDefault();
					s.close();
				}
			});

			// update window size
			$(window).bind('resize.simplemodal', function () {
				// redetermine the window width/height
				w = s.getDimensions();

				// reposition the dialog
				s.o.autoResize ? s.setContainerDimensions() : s.o.autoPosition && s.setPosition();

				if (ie6 || ieQuirks) {
					s.fixIE();
				}
				else if (s.o.modal) {
					// update the iframe & overlay
					s.d.iframe && s.d.iframe.css({height: w[0], width: w[1]});
					s.d.overlay.css({height: w[0], width: w[1]});
				}
			});
		},
		/*
		 * Unbind events
		 */
		unbindEvents: function () {
			$('.' + this.o.closeClass).unbind('click.simplemodal');
			$(document).unbind('keydown.simplemodal');
			$(window).unbind('resize.simplemodal');
			this.d.overlay.unbind('click.simplemodal');
		},
		/*
		 * Fix issues in IE6 and IE7 in quirks mode
		 */
		fixIE: function () {
			var s = this, p = s.o.position;

			// simulate fixed position - adapted from BlockUI
			$.each([s.d.iframe || null, !s.o.modal ? null : s.d.overlay, s.d.container], function (i, el) {
				if (el) {
					var bch = 'document.body.clientHeight', bcw = 'document.body.clientWidth',
						bsh = 'document.body.scrollHeight', bsl = 'document.body.scrollLeft',
						bst = 'document.body.scrollTop', bsw = 'document.body.scrollWidth',
						ch = 'document.documentElement.clientHeight', cw = 'document.documentElement.clientWidth',
						sl = 'document.documentElement.scrollLeft', st = 'document.documentElement.scrollTop',
						s = el[0].style;

					s.position = 'absolute';
					if (i < 2) {
						s.removeExpression('height');
						s.removeExpression('width');
						s.setExpression('height','' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + "px"');
						s.setExpression('width','' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + "px"');
					}
					else {
						var te, le;
						if (p && p.constructor === Array) {
							var top = p[0]
								? typeof p[0] === 'number' ? p[0].toString() : p[0].replace(/px/, '')
								: el.css('top').replace(/px/, '');
							te = top.indexOf('%') === -1
								? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'
								: parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';

							if (p[1]) {
								var left = typeof p[1] === 'number' ? p[1].toString() : p[1].replace(/px/, '');
								le = left.indexOf('%') === -1
									? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'
									: parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
							}
						}
						else {
							te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
							le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
						}
						s.removeExpression('top');
						s.removeExpression('left');
						s.setExpression('top', te);
						s.setExpression('left', le);
					}
				}
			});
		},
		/*
		 * Place focus on the first or last visible input
		 */
		focus: function (pos) {
			var s = this, p = pos && $.inArray(pos, ['first', 'last']) !== -1 ? pos : 'first';

			// focus on dialog or the first visible/enabled input element
			var input = $(':input:enabled:visible:' + p, s.d.wrap);
		},
		getDimensions: function () {
			var el = $(window);

			// fix a jQuery/Opera bug with determining the window height
			var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery < '1.3'
						|| $.browser.opera && $.browser.version < '9.5' && $.fn.jquery > '1.2.6'
				? el[0].innerHeight : el.height();

			return [h, el.width()];
		},
		getVal: function (v, d) {
			return v ? (typeof v === 'number' ? v
					: v === 'auto' ? 0
					: v.indexOf('%') > 0 ? ((parseInt(v.replace(/%/, '')) / 100) * (d === 'h' ? w[0] : w[1]))
					: parseInt(v.replace(/px/, '')))
				: null;
		},
		/*
		 * Update the container. Set new dimensions, if provided.
		 * Focus, if enabled. Re-bind events.
		 */
		update: function (height, width) {
			var s = this;

			// prevent update if dialog does not exist
			if (!s.d.data) {
				return false;
			}

			// reset orig values
			s.d.origHeight = s.getVal(height, 'h');
			s.d.origWidth = s.getVal(width, 'w');

			// hide data to prevent screen flicker
			s.d.data.hide();
			height && s.d.container.css('height', height);
			width && s.d.container.css('width', width);
			s.setContainerDimensions();
			s.d.data.show();
			s.o.focus && s.focus();

			// rebind events
			s.unbindEvents();
			s.bindEvents();
		},
		setContainerDimensions: function () {
			var s = this,
				badIE = ie6 || ie7;

			// get the dimensions for the container and data
			var ch = s.d.origHeight ? s.d.origHeight : $.browser.opera ? s.d.container.height() : s.getVal(badIE ? s.d.container[0].currentStyle['height'] : s.d.container.css('height'), 'h'),
				cw = s.d.origWidth ? s.d.origWidth : $.browser.opera ? s.d.container.width() : s.getVal(badIE ? s.d.container[0].currentStyle['width'] : s.d.container.css('width'), 'w'),
				dh = s.d.data.outerHeight(true), dw = s.d.data.outerWidth(true);

			s.d.origHeight = s.d.origHeight || ch;
			s.d.origWidth = s.d.origWidth || cw;

			// mxoh = max option height, mxow = max option width
			var mxoh = s.o.maxHeight ? s.getVal(s.o.maxHeight, 'h') : null,
				mxow = s.o.maxWidth ? s.getVal(s.o.maxWidth, 'w') : null,
				mh = mxoh && mxoh < w[0] ? mxoh : w[0],
				mw = mxow && mxow < w[1] ? mxow : w[1];

			// moh = min option height
			var moh = s.o.minHeight ? s.getVal(s.o.minHeight, 'h') : 'auto';
			if (!ch) {
				if (!dh) {ch = moh;}
				else {
					if (dh > mh) {ch = mh;}
					else if (s.o.minHeight && moh !== 'auto' && dh < moh) {ch = moh;}
					else {ch = dh;}
				}
			}
			else {
				ch = s.o.autoResize && ch > mh ? mh : ch < moh ? moh : ch;
			}

			// mow = min option width
			var mow = s.o.minWidth ? s.getVal(s.o.minWidth, 'w') : 'auto';
			if (!cw) {
				if (!dw) {cw = mow;}
				else {
					if (dw > mw) {cw = mw;}
					else if (s.o.minWidth && mow !== 'auto' && dw < mow) {cw = mow;}
					else {cw = dw;}
				}
			}
			else {
				cw = s.o.autoResize && cw > mw ? mw : cw < mow ? mow : cw;
			}

			s.d.container.css({height: ch, width: cw});
			s.d.wrap.css({overflow: (dh > ch || dw > cw) ? 'auto' : 'visible'});
			s.o.autoPosition && s.setPosition();
		},
		setPosition: function () {
			var s = this, top, left,
				hc = (w[0]/2) - (s.d.container.outerHeight(true)/2),
				vc = (w[1]/2) - (s.d.container.outerWidth(true)/2);

			if (s.o.position && Object.prototype.toString.call(s.o.position) === '[object Array]') {
				top = s.o.position[0] || hc;
				left = s.o.position[1] || vc;
			} else {
				top = hc;
				left = vc;
			}
			s.d.container.css({left: left, top: top});
		},
		watchTab: function (e) {
			var s = this;

			if ($(e.target).parents('.simplemodal-container').length > 0) {
				// save the list of inputs
				s.inputs = $(':input:enabled:visible:first, :input:enabled:visible:last', s.d.data[0]);

				// if it's the first or last tabbable element, refocus
				if ((!e.shiftKey && e.target === s.inputs[s.inputs.length -1]) ||
						(e.shiftKey && e.target === s.inputs[0]) ||
						s.inputs.length === 0) {
					e.preventDefault();
					var pos = e.shiftKey ? 'last' : 'first';
					s.focus(pos);
				}
			}
			else {
				// might be necessary when custom onShow callback is used
				e.preventDefault();
				s.focus();
			}
		},
		/*
		 * Open the modal dialog elements
		 * - Note: If you use the onOpen callback, you must "show" the
		 *	        overlay and container elements manually
		 *         (the iframe will be handled by SimpleModal)
		 */
		open: function () {
			var s = this;
			// display the iframe
			s.d.iframe && s.d.iframe.show();

			if ($.isFunction(s.o.onOpen)) {
				// execute the onOpen callback
				s.o.onOpen.apply(s, [s.d]);
			}
			else {
				// display the remaining elements
				s.d.overlay.show();
				s.d.container.show();
				s.d.data.show();
			}

			s.o.focus && s.focus();

			// bind default events
			s.bindEvents();
		},
		/*
		 * Close the modal dialog
		 * - Note: If you use an onClose callback, you must remove the
		 *         overlay, container and iframe elements manually
		 *
		 * @param {boolean} external Indicates whether the call to this
		 *     function was internal or external. If it was external, the
		 *     onClose callback will be ignored
		 */
		close: function () {
			var s = this;

			// prevent close when dialog does not exist
			if (!s.d.data) {
				return false;
			}

			// remove the default events
			s.unbindEvents();

			if ($.isFunction(s.o.onClose) && !s.occb) {
				// set the onClose callback flag
				s.occb = true;

				// execute the onClose callback
				s.o.onClose.apply(s, [s.d]);
			}
			else {
				// if the data came from the DOM, put it back
				if (s.d.placeholder) {
					var ph = $('#simplemodal-placeholder');
					// save changes to the data?
					if (s.o.persist) {
						// insert the (possibly) modified data back into the DOM
						ph.replaceWith(s.d.data.removeClass('simplemodal-data').css('display', s.display));
					}
					else {
						// remove the current and insert the original,
						// unmodified data back into the DOM
						s.d.data.hide().remove();
						ph.replaceWith(s.d.orig);
					}
				}
				else {
					// otherwise, remove it
					s.d.data.hide().remove();
				}

				// remove the remaining elements
				s.d.container.hide().remove();
				s.d.overlay.hide();
				s.d.iframe && s.d.iframe.hide().remove();

					// opera work-around
					s.d.overlay.remove();

					// reset the dialog object
					s.d = {};

			}
		}
	};
})(jQuery);

	
///////////////////////////////////////////////////////////////////////////////

/*
CSS Browser Selector v0.3.4 (Sep 29, 2009)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

///////////////////////////////////////////////////////////////////////////////

// http://bit.ly/ishiv | WTFPL License
window.innerShiv=function(){function h(c,e,b){return/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i.test(b)?c:e+"></"+b+">"}var c,e=document,j,g="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" ");return function(d,i){if(!c&&(c=e.createElement("div"),c.innerHTML="<nav></nav>",j=c.childNodes.length!==1)){for(var b=e.createDocumentFragment(),f=g.length;f--;)b.createElement(g[f]);b.appendChild(c)}d=d.replace(/^\s\s*/,"").replace(/\s\s*$/,"").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/(<([\w:]+)[^>]*?)\/>/g,h);c.innerHTML=(b=d.match(/^<(tbody|tr|td|col|colgroup|thead|tfoot)/i))?"<table>"+d+"</table>":d;b=b?c.getElementsByTagName(b[1])[0].parentNode:c;if(i===!1)return b.childNodes;for(var f=e.createDocumentFragment(),k=b.childNodes.length;k--;)f.appendChild(b.firstChild);return f}}();

///////////////////////////////////////////////////////////////////////////////

/* Checkout Guest Registration Form */
if (smarty_vars.divinity.page == 'checkout' && smarty_vars.divinity.action == 'receipt')  {
	jQuery(document).ready(function() {
		jQuery('#register-guest').delegate('form', 'submit', function() {
			divinity.box.loading();
			var data = jQuery.param(jQuery(this).find('input,select').get());
			jQuery.ajax({
				"type": 'POST',
				"url": smarty_vars.rel_html_url + '?page=checkout&action=guest',
				"data": data,
				"success" : function(o) {
					divinity.box.close();
					jQuery('#register-guest').html(o).find('input[name="password"]').focus();
				} 
			});
			return false;
		});
	});
}



TC.fetch_wishlists = function (wrapper) { 
	wrapper = wrapper || jQuery('body');
	jQuery.ajax({
		url: smarty_vars.rel_html_url,
		data: 'page=item_ajax&action=wishes',
		type: 'POST',
		dataType: 'json',
		success: function (o) {
			for (var i in o) {
				if (smarty_vars.divinity.page != "item"){ 
				wrapper.find('a[href*="page=wishlists&action=add&id=' + o[i].sku + '"]')                               
					.addClass('added-to-wishlist')
					.removeClass('add-to-wishlist');
				}
			}
		}
	});
}

jQuery(document).ready(function() {
	
	// Mark as added to wishlist
	//
	jQuery('body a').filter(function() {
		return this.href.indexOf('page=wishlists') > -1 
			&& this.href.indexOf('action=add') > -1;
	}).click(function () { 
		TC.wishlist_link = jQuery(this);
	});

	if (smarty_vars.divinity.page == 'item') {
		jQuery('#facebook-stuff-wishlist, #pdp-item-details footer .add-to-wishlist').each(function () {
			jQuery(this).attr(
				'href',
				jQuery(this).attr('href') + location.hash.substr(1).toUpperCase()
			);
		});
	}

	// Fetch & mark wishlist items
	//
	TC.fetch_wishlists();

}); 
///////////////////////////////////////////////////////////////////////////////

/**
 * Legacy crap copied from mas_assets/common.js
 */
jQuery(document).ready(function () {

    /**
    * CHECKOUT Step 1 of 3: Authentication; sets the radio button
    * next to the password field to 'checked'
    */
    jQuery("input[name='password']").focus(function () {
        jQuery("input[value='login']").attr("checked", "checked");
    });

    /**
    * Initialize jCarousel for RSS feeds
    */
    if (typeof jQuery.fn.jcarousel != "function") {
        jQuery.fn.jcarousel = function() {}
        }

    jQuery('#rss-carousel').jcarousel({
        "vertical": true,
        "scroll": 2
    });

    jQuery('.front-page-products').jcarousel({
        "vertical": false
    });

    /**
    * Dropdown menu for category selection
    */
    jQuery("#feeds-selector").change(function () {

        var selected = jQuery(this).val();
        var products_template = jQuery("#products_template").val();
        var url = smarty_vars['html_url']+"?type=bare&page=rss&action=products_list&feed=" + selected + "&products_template=" + products_template;
        jQuery(".feeds-content *").remove();
        jQuery(".feeds-content").append('<ul class="jcarousel jcarousel-skin-strict"></ul>');

        jQuery.ajax({
            url:  url,
            cache: false,
            dataType: 'html',
            success: function(html){
                jQuery("ul.jcarousel").append(html);
                jQuery('ul.jcarousel').jcarousel({
                    "vertical": true,
                    "scroll": 2
                });
            }
        });
    });

});

/** wtf ? */
function round(number, digits) {
        var divisor = Math.pow(10, digits);
        return Math.round(number * divisor) / divisor;
        }

/** ... */
function swap_product_image(img, normal_i) {
	
	var i2 = document.images['product_image'], 
		a2 = jQuery(i2).parent('a')[0],
		a1 = jQuery(img).parent('a')[0]; 
	
	i2.src = img.src;
	i2.src = normal_i;
	i2.alt = img.alt;

	a2.title = a1.title;
	a2.href = a1.href;
		
	return false;
        }
