

jQuery(function(){
	
	// alias jQuery to $j
	$j = jQuery;
	
	// set nav
	var section;
	if ($j('body').hasClass('home')) section='home';
	if ($j('body').hasClass('company')) section='company';
	if ($j('body').hasClass('products')) section='products';
	if ($j('body').hasClass('solutions')) section='solutions';
	if ($j('body').hasClass('ideas')) section='ideas';
	if ($j('body').hasClass('none')) section='';
	
	// check for platform
	if (navigator.appVersion.indexOf("Win")!=-1) $j('body').addClass('pc');
	if (navigator.appVersion.indexOf("Mac")!=-1) $j('body').addClass('mac');
	//if (navigator.appVersion.indexOf("X11")!=-1) $j('body').addClass('unix');
	//if (navigator.appVersion.indexOf("Linux")!=-1) $j('body').addClass('linux');
	
	// check for iphone, ipad
	if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
		$j('body').addClass('ios');
	}
	
	initPZ(section);
	
});




/* ----------------------------------------
init
---------------------------------------- */

function initPZ(section) {
	
	// note: some scripts are in prototype, others are in jquery; be sure to use the appropriate selector notation
	
	// fix page layout
	$j('#pzHead').addClass('clearfix');
	$j('#pzBody').addClass('clearfix');
	
	// init sections
	if ($j('#pzHead') && !$j('#pzHead').html()) initHeader(section);
	if ($j('#pzFoot') && !$j('#pzFoot').html()) {
		initFooter();
	} else {
		initCartModule($j('#pzCart').attr('href')); //'views/pzCart.tpl');
	}
	if ($j('#pinaFacts')) initPinaFacts();
	if ($j('#pzFAQ')) initFAQ();
	
	if ($j('#pzFeatureImage')) pzHome();
	if ($j('#pzViewerCtrl') && $j('#pzViewerImageContainer')) pzViewer();
	
	if ($j('#itemSelector')) new pzItemSelector('itemSelector');
	if ($('pzFilter') && $('pzItemList')) new pzFilter('pzFilter', 'pzItemList');
	
	if ($('pzDialogWindow')) initDialogWindow();
	if ($j('table.account')) initAccountTables();
	
	if ($j('#design_tool_selector')) initDesignToolSelector();
	if ($j('#account_artwork_selector')) initAccountArtworkSelector();
	
}

function initAccountTables() {
	$j('table.account tbody tr.active').mouseenter(function(event){
		$j(this).addClass('hover');
	});
	$j('table.account tbody tr.active').mouseleave(function(event){
		$j(this).removeClass('hover');
	});
	$j('table.account tbody tr.active').click(function(event){
		$j('table.account tbody tr.selected').removeClass('selected');
		$j(this).addClass('selected');
		$j('#order').load($j(this).attr('href'));
	});
}

/* ----------------------------------------
init header
---------------------------------------- */

function initHeader(section) {
	$j('#pzHead').load('views/pzHead.tpl', function() {
		if (section != '') {
			$j('#'+section+'Nav').addClass('selected');
		}
	});
}

/* ----------------------------------------
init footer
---------------------------------------- */

function initFooter() {
	$j('#pzFoot').load('views/pzFoot.tpl', function() {
		initCartModule($j('#pzCart').attr('href'));
	});
}

/* ----------------------------------------
FAQ
---------------------------------------- */

function initFAQ() {
	var faqItems = $j('#pzFAQ .faqItem');
	faqItems.click(function(event) {
		if (!$j(this).hasClass('selected')) {
			$j('#pzFAQ .faqItem').removeClass('selected');
			$j(this).addClass('selected');
		}
	});
}

/* ----------------------------------------
pinaFacts
---------------------------------------- */

function initPinaFacts() {
	
	var pinaFacts = $j('#pinaFacts .pinaFact');
	var len = pinaFacts.length;
	if (pinaFacts.length > 0) {
		pinaFacts.each(function() {
			$j(this).hide();
		});
		var randFact = pinaFacts.eq(Math.floor(Math.random() * len));
		randFact.addClass('selected');
		randFact.fadeIn();
		setTimeout(swapPinaFacts, 10*1000);
	}
}

function swapPinaFacts() {
	if ($j('#pinaFacts')) {
		var cFact = $j('#pinaFacts .selected')
			.fadeOut(250)
			.removeClass('selected');
		if (cFact.next().length > 0) {
			cFact.next()
				.fadeIn()
				.addClass('selected');
		} else {
			cFact.siblings().first()
				.fadeIn()
				.addClass('selected');
		}
		setTimeout(swapPinaFacts, 10*1000);
	}
}

/* ----------------------------------------
account section (called from page)
---------------------------------------- */

function accountDisplay(showElmt, hideElmt) {
	if (showElmt) $j('#'+showElmt).show();
	if (hideElmt) $j('#'+hideElmt).hide();
}



/* ----------------------------------------
Design Tool
---------------------------------------- */

// ********************
var designToolWindow = null;
function openDesignTool(url) {
	var props = "status=0,toolbar=0,location=0,menubar=0,directories=0,personalbar=0,titlebar=1,resizable=1,scrollbars=auto,left=0,top=0,fullscreen=1,height=" + screen.height + ",width=" + screen.width;
	
	if (designToolWindow == null || designToolWindow.closed) {
		designToolWindow = window.open(url, "Design_Tool", props);
	} else {
		designToolWindow.focus();
	}
}


function initDesignToolSelector() {
	
	// reset options
	//document.getElementById('design_tool_selector').reset();
	//$j('#imprinting_type_id').attr('disabled', 'disabled');
	
	// change handler
	$j('#product_id').change(function() {
		
		if ($j(this).val() != "null") {
			// get product_id and load compatible imprinting options
			var product_id = $j(this).val();
			var url = $j('#product_id').attr('url') + "?product_id=" + product_id;
			$j('#imprinting_type_id')
				.load(url)
				.removeAttr('disabled');
		} else {
			// reset and disable custom imprinting menu
			$j('#imprinting_type_id').attr('disabled', 'disabled');
			$j('#imprinting_type_id').val('null');
		}
		
	});
	
	// click handler
	$j('#launch_tool_btn').click(function() {
		if ($j('#product_id').val() != "null" && $j('#product_id').val() != "" && $j('#imprinting_type_id').val() != "null" && $j('#imprinting_type_id').val() != "") {
			var url = $j('#design_tool_selector').attr('url') + '?' + $('design_tool_selector').serialize();
			openDesignTool(url);
		} else {
			alert("Please select a 'Product' and 'Imprinting Type'.");
		}
	});
	
}
function initAccountArtworkSelector() {
	//alert($j('.artwork_selector'));
	$j('.artwork_selector').change(function() {
		if ($j(this).val() == 'new_artwork') {
			//alert($j(this).find("[value='new_artwork']").attr('url'));
			window.location = $j(this).find("[value='new_artwork']").attr('url');
		}
	});
}

/* ----------------------------------------
pzCart (jQuery)
---------------------------------------- */

var cart; 
var cartWindow;

// pzCartModule
function initCartModule(url) {
	
	// ***temp: modify cart to support new cart system
	/*
	if ($j('#utils .cart').html = "") {
		$j('#utils .cart').html("<p class='title' id='cartTitle'>cart</p><p class='info' id='cartInfo'>No items in your cart</p>");
	}
	$j('#cartTab .info').remove();
	*/
	
	
	$j('#pzCart').load(url, function() {
		
		// init cart class
		cart = pzCart($j('#pzCart')); //new pzCart($j('#pzCart')); //****
		
		// set initial cart position
		//$j('#pzCart').css({ bottom: -$j('#cartMain').outerHeight() });
		//$j('#pzCart').css({ bottom: -$j('#pzCart').outerHeight() });
		
		// observe cart tab (in open state)
		$j('#cartTab').click(function() {
			toggleCart();
		});
		$j('#continue_shopping.button').click(function() {
			toggleCart();
		});
		
		// observe cart tab (in closed state)
		$j('#pzUtils .cart').click(function() {
			toggleCart();
		});
		
		// ***CART create pzDialogWindow instead of cart
		cartWindow = new pzDialogWindow($('pzCart'), $('cartBlock'));
		//cartWindow.show();
		//cartWindow.setPosition.delay(.5);
		
	});
	
}


function lockCartPosition() {
	//$j('#pzCart').css({ top: $j(window).height() - 40, bottom: 'auto' });
}

function unlockCartPosition() {
	//$j('#pzCart').css({ top: 'auto' });
}

function toggleCart() {
	$j('#pzCart').toggleClass('closed');
	
	if ($j('#pzCart').hasClass('closed')) {
		
		// open cart
		//$j('#pzCart').css({ zIndex:'205' });
		//$j('#cartBlock').css({ display:'block', zIndex:'204' });
		//$j('#cartClose').css({ display:'block' });
		//$j('#cartInfo').css({ display:'none' });
		
		/*
		$j('#pzCart').animate({
			bottom: 80
		}, 500, function() {
			//$j('#pzCart').css({ zIndex:'205' });
		});
		*/
		
		cartWindow.show();
		cartWindow.setPosition.delay(.5);
		
	} else {
		// close cart
		
		//$j('#pzCart').css({ zIndex:'205' });
		//$j('#cartBlock').css({ display:'none', zIndex:'100' });
		
		//$j('#cartClose').css({ display:'none' });
		//$j('#cartInfo').css({ display:'block' });
		
		/*
		$j('#pzCart').animate({
			bottom: -$j('#cartMain').outerHeight()
		}, 500, function() {
			$j('#pzCart').css({ zIndex:'201' });
		});
		*/
		
		cartWindow.hide();
	}
	
}



var pzCart = function(elmt) {
	
	// set class variables
	var elmt = elmt;
	var url = $j('#cartMain').attr('url');
	
	// init remove button
	$j('#remove_item').click(function() {
		var elmt = $j('#cart_list_items .selected');
		if (elmt) _removeItem(elmt.attr('id'));
	});
	
	// load initial cart data
	_update();
	
	// *** uncomment for testing with static data ***
	//_loadItemDetail('data/cart_detail.tpl');
	
	function _removeItem(rowID) {
		var params = {
			action:'remove_item',
			cart_item_id:rowID
		};
		_update(params);
	}
	
	// called from public method addItem (see below)
	function _addItem(serializedFormData) {
		var params = {
			action:'add_item',
			form_data:serializedFormData
		};
		_update(params);
	}
	
	function _updateItem(rowID, qty) {
		var params = {
			action:'update_item',
			cart_item_id:rowID,
			quantity:qty
		};
		_update(params);
	}
	
	function _update(params) {
		
		if (!params) params = {action:'update_list'};
		if (params.type == 'add_item' || params.type == 'update_list') {
			// lock cart position (sets position to 'top'; gets unlocked in onUpdate)
			// ***CART
			//lockCartPosition();
		}
		
		// load cart list data 
		$j('#cart_list_items').load(url, params, function() {
			_onUpdate(this);
		});
		
	}
	
	function _onUpdate(elmt) {
		
		//elmt.html(transport.responseText);
		
		var totalQty = 0;
		var totalPrice = 0;
		
		// init item listeners & calc totals
		var elmts = $j(elmt).children();
		elmts.each(function(i) {
			
			// listen for click event for item row
			$j(this).click(function(event) {
				_itemListener(event);
			});
			
			// listen for onChangeEvent for item qty
			$j(this).find('.qty_input').change(function(event){
				//var rowID = $j(event.target).closest('tr').index();
				var rowID = $j(event.target).closest('tr').attr('id');
				var qty = $j(event.target).val();
				_updateItem(rowID, qty);
			});
			
			// calc totals
			totalQty += Number($j(this).find('.qty_input').val());
			totalPrice += Number($j(this).find('.price').html().substring(1));
			
		});
		
		// *** need to change this to check for number of items (qty can equal 0 but not be empty)
		if (totalQty > 0) {
			// update totals
			$j('#cartQtyTotal').html(totalQty);
			$j('#cartPriceTotal').html('$' + totalPrice.toFixed(2));
			// update cart tab info
			$j('#cartInfo').html(totalQty + ' Items &mdash; $' + totalPrice.toFixed(2));
			$j('#headCartInfo #qtyText').html(totalQty + ' Items');
		} else {
			// update totals
			$j('#cartQtyTotal').html("");
			$j('#cartPriceTotal').html("");
			// update cart tab info
			$j('#cartInfo').html("No items in your cart");
			$j('#headCartInfo #qtyText').html('0 Items');
		}
		
		// update cart position (sets position to 'bottom')
		// ***CART
		//unlockCartPosition.delay(1);
		
		// select first item
		_selectItem($j(elmts).eq(0));
	}
	
	function _itemListener(e) {
		_selectItem($j(e.target).closest('tr'));
	}
	
	function _selectItem(elmt) {
		// set selected
		$j(elmt).siblings().removeClass('selected').end()
			.addClass('selected');
		// load item detail
		_loadItemDetail($j(elmt).attr('url'));
	}
	
	function _loadItemDetail(url) {
		// *** smooth out item detail transition (i.e. fadeIn/FadeOut)
		// *** also sometimes does not load - FIX THIS
		$j('#cart_item_detail_container').load(url, function() {
			$j(this).css({'display':'block'});
		});
	}
	
	// public functions
	return {
		addItem: function(serializedFormData) {
			// animate background color
			//$j("#cartTab")
			$j("#utils .cart")
				.animate( { backgroundColor: '#00FF00' }, 100)
				.animate( { backgroundColor: '#16325C' }, 1000)
			_addItem(serializedFormData);
			// # added 10.25.2011 - need to test
			toggleCart();
		}
	}
	
}






/* ----------------------------------------
pzItemList (jQuery)
---------------------------------------- */

var pzItemList = function(listElmt) {
	//console.log('pzItemList');
	
	var listElmt = $j('#'+listElmt);
	
	// initList(); // <!-- called from loadList when new list loaded
	
	function _loadList(url) {
		listElmt.load(url, function(){
			initList();
		});
	}
	
	function initList() {
		var items = $j('#pzItemList .item');
		var timer = 0;
		items.each(function() {
			$j(this).prepend('<div class="icon"></div>')
				.mouseenter(function(event){
					itemOverHandler(event);
				})
				.mouseleave(function(event){
					itemOutHandler(event);
				})
				.click(function(event){
					itemClickHandler(event);
				})
				//.hide()
				//.delay(.15 * timer * 1000)
				//.fadeIn(500)
				.find('.icon').css({opacity:0}).end();
			timer++;
		});
		
	}
	
	function itemOverHandler(event) {
		//console.log(event.currentTarget);
		var elmt = $j(event.currentTarget);
		//console.log(elmt);
		if (!$j(elmt).hasClass('selected')) {
			$j('#pzItemList .selected').each(function(){
				deselectItem(this);
			});
			selectItem(elmt);
		} else {
			// do nothing
		}
	}

	function itemOutHandler(event) {
		//console.log(event.currentTarget);
		var elmt = $j(event.currentTarget);
		//console.log(elmt);
		if ($j(elmt).hasClass('selected')) {
			$j('#pzItemList .selected').each(function(){
				deselectItem(this);
			});
		} else {
			// do nothing
		}
	}

	function itemClickHandler(event) {
		//console.log(event.currentTarget);
		var elmt = $j(event.currentTarget);
		if (!$j(elmt).hasClass('selected')) {
			$j('#pzItemList .selected').each(function(){
				deselectItem(this);
			});
			selectItem(elmt);
		} else {
			window.location = elmt.attr('url');
		}
	}

	function resizeHandler() {
		var w =$j(window).width();
		var h = $j(window).height();
		var d = h - 160 - 10 -10 - 20 - 40;
		$('#pzItemList').css({ height:d });
	}

	function selectItem(elmt) {
		$j(elmt).stop().animate({height:300}, 250).css({opacity:100}).addClass('selected')
			.find('img').stop().animate({height:280}, 250).end()
			.find('.icon').stop().css({opacity:0}).delay(250).animate({opacity:1});
	}

	function deselectItem(elmt) {
		$j(elmt).stop().animate({height:120}, 250).css({opacity:100}).removeClass('selected')
			.find('img').stop().animate({height:100}, 250).end()
			.find('.icon').stop().css({opacity:0});
		//console.log($j(elmt).find('.icon'));
	}
	
	return {
		loadList: function(url) {
			_loadList(url);
		},
		displayItem:function(elmt) {
			_displayItem(elmt);
		}
	}
	
}







/* ----------------------------------------
pzHome (jQuery)
---------------------------------------- */

	
var pzHome = function() {
		
	var self = this;
	
	// init pzItemList
	var featureImg = $j('#pzFeatureImage');
	var featureInfo = $j('#pzFeature');
	var delay = 12; //12;
	var total = $j('#pzFeatureImage ul li').length;
	var currentID = Math.random()*total;
	
	// build nav
	var len = $j('#pzFeature ul li').length;
	$j('#pzFeature ul li').each(function() {
		var featItem = $j(this);
		var index = $j(this).index();
		$j(featItem).append('<div class="featureNav"></div>');
		for (i=1;i<=len;i++) {
			if (i == index+1) {
				$j(featItem).children('.featureNav').append('<div class="fni selected">' + i + '</div>');
			} else {
				$j(featItem).children('.featureNav').append('<div class="fni">' + i + '</div>');
			}
		};
	});
	
	// nav handlers
	$j('#pzFeature .featureNav .fni')
		.mouseover(function() {
			$j(this).addClass('hover');
		})
		.mouseleave(function() {
			$j(this).removeClass('hover');
		})
		.click(function() {
			if ($j(this).hasClass('selected')) {
				// do nothing
			} else {
				nextListener($j(this).index());
			}
		});
	
	// hide all
	$j('#pzFeatureImage ul li').hide();
	$j('#pzFeature ul li').hide();
	$j('#pzFeatureImage').hide();
	$j('#pzFeature').hide();
	
	// show random
	$j('#pzFeatureImage ul li').eq(currentID).show();
	$j('#pzFeature ul li').eq(currentID).show();
	
	// fadeIn
	setTimeout(fadeInFeature, 1000);
	
	// start timer
	var timer = setTimeout(function(){nextListener(null)}, delay * 1000);
	
	// resize handler
	$j(window).resize(function(event) {
		resizeHandler();
	});
	
	
	function nextListener(featIndex) {
		//console.log(featIndex);
		// reset timer
		clearTimeout(timer);
		transitionFeature(featIndex);
		timer = setTimeout(function(){nextListener(null)}, delay * 1000);
	}
	function transitionFeature(featIndex) {
		fadeOutFeature();
		setTimeout(function(){nextFeature(featIndex)}, 1000);
		setTimeout(fadeInFeature, 1000);
	}
	function nextFeature(featIndex) {
		// hide currentID
		$j('#pzFeatureImage li').eq(currentID).hide();
		$j('#pzFeature li').eq(currentID).hide();
		
		if (featIndex == undefined || featIndex == null) {
			//console.log('featIndex undefined');
			// advance currentID
			currentID++;
			if (currentID >= total) {
				currentID = 0;
			}
		} else {
			currentID = featIndex;
		}
		//console.log("cID:" + currentID + "; featIndex:" + featIndex);
		
		// show currentID
		$j('#pzFeatureImage li').eq(currentID).show();
		$j('#pzFeature li').eq(currentID).show();
	}
	function fadeInFeature() {
		featureImg.fadeIn(1000);
		featureInfo.fadeIn(1000);
		setTimeout(resizeHandler, 100);
	}
	function fadeOutFeature() {
		$j('#pzFeatureImage').fadeOut(500);
		$j('#pzFeature').fadeOut(500);
	}
	function resizeHandler() {
		var ypos = ($j(window).height() - $j('#pzFeatureImage li')
			.eq(currentID).find('img').height()) / 2;
		var xpos = ($j(window).width() - $j('#pzFeatureImage li')
			.eq(currentID).find('img').width()) / 2;
		$j('#pzFeatureImage ul').css({ top: ypos, left: xpos });
	}
	
}







/* ----------------------------------------
pzItemSelector (jQuery)
---------------------------------------- */

var pzItemSelector = function(elmt) {
	
	// set class variables
	var elmt = $j(elmt);
	var url = $j('#so_data').attr('url');
	
	// set display
	$j('selector_item_instructions').css({ display:'block' });
	$j('selector_item_detail_container').css({ display:'none' });
	//$j('view_compatible_accessories').css({ display:'none' });
	
	// *** uncomment for testing ***
	//_loadItemDetail('data/detail.tpl');
	
	_loadOptions(url, $('so1_container'));
	
	function _loadOptions(url, elmt) {
		
		$j(elmt).load(url, function() {
			var elmts = $j(elmt).find('ul').children();
			if (elmts.length > 1) {
				elmts.each(function(i) {
					$j(this).addClass('so_option');
					$j(this).click(function(event){
						_optionsListener(event);
					});
					if ($j(this).hasClass('default')) {
						_optionHandler($j(this));
					}
				});
			} else {
				_optionHandler($j(elmts).eq(0));
			}
		});
	}
	
	function _optionsListener(event) {
		_optionHandler($j(event.target).parent());
	}
	
	function _optionHandler(elmt) {
		// set selected
		$j(elmt).siblings().removeClass('selected').end()
			.addClass('selected');
		
		// clear all columns after this one
		$j(elmt).parent().parent().nextAll().each(function(i){ 
			$j(this).html("");
		});
		
		// reset detail
		_resetItemDetail();
		
		// check if next column is 'active' and load next column or itemDetail
		if ($j(elmt).parent().parent().next().hasClass('active')) {
			_loadOptions($j(elmt).attr('url'), $j(elmt).parent().parent().next());
		} else {
			_loadItemDetail($j(elmt).attr('url'));
		}
		
	}
	
	function _loadItemDetail(url) {
		var elmt = $j('#selector_item_detail_container');
		$j(elmt).load(url, function(){
			
			// set display
			$j('#selector_item_instructions').css({ display:'none' });
			$j('#selector_item_detail_container').css({ display:'block' });
			$j('#pzBody .add_options').css({ display:'none' });
			$j('#pzBody .buy_options').css({ display:'block' });
			//$j('#view_compatible_accessories').css({ display:'block' });
			
			// init listeners
			$j('#pzBody .buy_from_us').click(function(event) { _onClickBuyFromUs() });
			$j('#pzBody .add_to_cart').click(function(event) { _onClickAddToCart() });
			$j('#pzBody .notify_btn').click(function(event) { _onClickNotify() });
			
			// show add options if preselected
			if($j('#pzBody .add_options').hasClass('selected')) {
				_onClickBuyFromUs();
			}
			
		});
		
	}
	
	function _resetItemDetail() {
		$j('#selector_item_instructions').css({ display:'block' });
		$j('#selector_item_detail_container').css({ display:'none' });
		//$j('#view_compatible_accessories').css({ display:'none' });
	}
	
	function _onClickBuyFromUs(event) {
		$j('#pzBody .buy_options').css({ display:'none' });
		$j('#pzBody .add_options').css({ display:'block' });
	}
	
	function _onClickAddToCart(event) {
		// add item to cart
		var qty = $j('#pzBody .qty_input input').val();
		if (qty > 0 && qty < 50) {
			var formData = $j('#pzBody .add_to_cart_form').serialize();
			cart.addItem(formData);
		} else if (qty >= 50) {
			alert("Quantity must be less than 50. To purchase more than 50 of an item please call us at 1-800-926-7462 or 1-415-206-9582.");
		}
		
		// set quantity to zero
		$j('#pzBody .qty_input input').val("");
	}
	
	function _onClickNotify() {
		
		var formData = $j('#pzBody .out_of_stock_form').serialize(true);
		
		var url = $j('#pzBody .out_of_stock_form .notify_btn').attr('url');

		new Ajax.Request(url, {
			method: 'post',
			parameters: formData,
			onSuccess: function(transport){
				
				if(transport.responseText == 'success'){
					$j('#pzBody .out_of_stock_email').css({display:'none'});
					$j('#pzBody .out_of_stock_error').css({display:'none'});
					$j('#pzBody .out_of_stock_confirm').css({display:'block'});
				}
				else{

					$j('#pzBody .out_of_stock_error')[0].innerHTML = transport.responseText;
					$j('#pzBody .out_of_stock_error').css({display:'block'});
				}
				
			}.bind(this)
		});
		
	}
	
};






/* ----------------------------------------
pzViewer (jQuery)
---------------------------------------- */

var pzViewer = function() {
	
	var ctrlElmt = $j('#pzViewerCtrl');
	var imgElmt = $j('#pzViewerImageContainer');
	
	if ($j('#pzViewerCtrl li').length <= 1) {
		$j('#pzViewerCtrl').hide();
	} else if ($j('#pzViewerCtrl li').length <= 4) {
		$j('#ctrlLeft').hide();
		$j('#ctrlRight').hide();
	} else {
		$j('#ctrlRight').click(function(event) { _onCtrlRightClick(event) });
		$j('#ctrlLeft').click(function(event) { _onCtrlLeftClick(event) });
		$j('#ctrlLeft').hide();
	}
	//$j('#pzViewerCtrl li').click(function(event){ _onThumbClick(event) });
	var delayTimer;
	$j('#pzViewerCtrl li').mouseover(function(event){ 
		clearTimeout(delayTimer);
		delayTimer = setTimeout(function(){delayThumbClick(event)}, 150);
	});
	function delayThumbClick(event) {
		_onThumbClick(event);
	}
	
	function _onThumbClick(event) {
		var id = $j(event.currentTarget).attr('id').substring(6);
		$j('#ctrlSelector').animate({'left':71 * Number(id)}, 250);
		$j('#pzViewerImages').animate({'left':-590 * Number(id)}, 250);
	};
	
	function _onCtrlRightClick(event) {
		var xoff = $j('#pzViewerThumbs').position().left;
		if (xoff < 0) {
			var tx = -71*4;
		} else {
			var tx = (-71*4) + 17;
		}
		$j('#ctrlRight').hide();
		$j('#ctrlLeft').show();
		$j('#pzViewerThumbs').animate({'left':tx}, 250);
	};
	function _onCtrlLeftClick(event) {
		$j('#ctrlRight').show();
		$j('#ctrlLeft').hide();
		$j('#pzViewerThumbs').animate({'left':0}, 250);
	};
	
};







/* ----------------------------------------
safe debugger (jQuery)
---------------------------------------- */

jQuery.fn.debug = function() {
	return this.each(function(i){
		jQuery.log(i+": "+this);
	});
};
jQuery.log = function(msg) {
	if(window.console) {
		console.log(msg);
	} else {
		//alert(message);
	}
};
//jQuery.log('debug active:jQuery(selector).debug() or jQuery.log("msg")');









/* ----------------------------------------
pzDialogWindow (Prototype)
---------------------------------------- */

var dialogWindow;

function initDialogWindow() {	
	dialogWindow = new pzDialogWindow($('pzDialogWindow'), $('pageBlock'));
}

var pzDialogWindow = Class.create();
pzDialogWindow.prototype = {
	
	initialize: function(dialogElmt, blockElmt) {
		
		//console.log(blockElmt);
		
		// class variables
		this.dialogElmt = $(dialogElmt);
		this.blockElmt = $(blockElmt);
		
		// set display
		this.dialogElmt.hide();
		this.blockElmt.hide();
		
	},
	
	show: function() {
		
		//console.log(this.blockElmt);
		
		// set display
		this.blockElmt.appear({ duration: 0 });
		this.dialogElmt.appear({ duration: .25 });
		
		// start window resize listener
		Event.observe(window, 'resize', this.resizeListener.bind(this), false);
	},
	
	hide:function() {
		
		// set display
		this.blockElmt.fade({ duration: 0 });
		this.dialogElmt.fade({ duration: .25 });
		
		// stop window resize listener
		Event.stopObserving(window, 'resize', this.resizeListener, false);
	},
	
	load: function(url) {
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				
				// replace content
				if (this.dialogElmt.down()) this.dialogElmt.down().remove();
				this.dialogElmt.insert(transport.responseText);
				
				// init close button handler
				if ($$('#pzTabModule .tab')) {
					// tab listener
					Event.observe($$('#pzTabModule .tab')[0], 'click', this.hide.bind(this), false);
				}
				
				// check for type of window and initialize
				if ($('pzAccessories')) {
					// init accessories class
					accessories = new pzAccessories($('pzAccessories'));
				}
				
				this.show();
				this.setPosition.delay(.5); // <-- *** needs to be done again after everything loaded
				
			}.bind(this)
		});
		
	},
	
	resizeListener: function() {
		this.setPosition();
	},
	
	setPosition: function() {
		
		//console.log('setPosition');
		
		//var ypos = (document.viewport.getHeight() / 2) - ($$('.tabModule')[0].getHeight() / 2);
		//$$('.tabModule')[0].setStyle({ top:ypos+'px' });
		
		// set element height (jquery!)
		var ypos;
		$j('.tabModule').each(function(i, element) {
			if ($j('body').hasClass('ios')) {
				//alert('ios');
				ypos = ($j(document).height() / 2) - ($j(element).innerHeight() / 2);
			} else {
				ypos = ($j(window).height() / 2) - ($j(element).innerHeight() / 2);
			}
			$j(element).css({top:ypos});
			//alert($j(element).innerHeight());
		});
		
		// set block height (jquery!)
		$j('.block').each(function(i, element) {
			$j(element).height($j(document).height());
		});
		
	}
	
}






/* ----------------------------------------
accessories (Prototype)
---------------------------------------- */

var pzAccessories = Class.create();
pzAccessories.prototype = {
	
	initialize: function(elmt, options) {
		// set class variables
		this.elmt = $(elmt);
		this.options = Object.extend({
			// no options
		}, options || {});
		
		this.selectedItem = null; // not used
		
		// register tabs
		var tabs = $('accessoriesMain').select('.accessories_nav tr');
		tabs.each(function(elmt) {
			if(!elmt.hasClassName('null')) { //*** FIX CSS not to show hover state when 'null'
				elmt.observe('click', function(event) {
					this.selectTab(event.findElement('tr'));
				}.bind(this));
			}
		}.bind(this));
		
		// select 1st tab
		this.selectTab(tabs[0]);
	},
	
	selectTab: function(elmt) {
		
		// select tab
		if ($('accessoriesMain').down('.accessories_nav .selected')) {
			$('accessoriesMain').down('.accessories_nav .selected').removeClassName('selected');
		}
		elmt.addClassName('selected');
		
		// hide item lists
		$('accessoriesMain').select('.selector_list tbody').each(function(elmt) { elmt.hide() });
		$('accessoriesMain').select('.selector_list tbody.accessories_nav').each(function(elmt) { elmt.show() });
		
		// show selected list
		var id = elmt.readAttribute('class').split(" ")[0]; // split to prevent 'selected' as part of id
		var listElmt = $('accessoriesMain').select('.selector_list tbody.' + id)[0].show();
		
		// init item list
		this.initItemList(listElmt);
		
	},
	
	initItemList: function(elmt) {
		// item row listners
		var rowElmts = elmt.childElements();
		rowElmts.each(function(rowElmt) {
			rowElmt.observe('click', function(event) {
				this.itemListener(event);
			}.bind(this));
		}.bind(this));
		
		// select first item
		this.selectItem(rowElmts[0]);
	},
	
	itemListener: function(e) {
		var elmt = Event.element(e).up('tr');
		this.selectItem(elmt);
	},
	
	selectItem: function(elmt) {
		// clear selected
		var siblings = elmt.siblings();
		siblings.each(function(i) {
			i.removeClassName('selected');
		});
		// set selected
		elmt.addClassName('selected');
		// load item detail
		this.loadItemDetail(elmt.readAttribute('url'));
	},
	
	loadItemDetail: function(url) {
		
		var elmt = $('accessories_item_detail_container');
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				// remove existing (if it exists)
				if (elmt.down()) elmt.down().remove();
				// insert loaded content
				elmt.insert(transport.responseText);
				// display item
				elmt.setStyle({ display:'block' });
				// add item listener
				$('pzAccessories').down('.add_to_cart').observe('click', this.addItemListener.bind(this));
				// reposition dialog window
				dialogWindow.setPosition.delay(.1);
				
			}.bind(this)
		});
		
	},
	
	addItemListener: function(e) {
		// add item to cart
		var formData = $('pzAccessories').down('.add_to_cart_form').serialize();
		cart.addItem(formData);
		// reset quantity to zero
		$('pzAccessories').down('.qty_input').down('input').value = "";
	}
	
}


/* ----------------------------------------
Email a friend (JQuery)
---------------------------------------- */

function submitEmailAFriend() {
	
	$j('#pzEmail .error_message').remove();
	
	var hasError = false;
	var emailReg = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	
	var nameVal = $j('#pzEmail input[name="name"]').val();
	var emailVal = $j('#pzEmail input[name="email"]').val();
	
	if (emailVal == '' || nameVal == '') {
		$j("#pzEmail .pageContent").prepend('<div class="error_message"><p>Please enter a name and a valid email address.</p></div>');
		hasError = true;
	} else if (!emailReg.test(emailVal)) {
		$j("#pzEmail .pageContent").prepend('<div class="error_message"><p>Please enter a valid email address.</p></div>');
		hasError = true;
	}
	
	if (!hasError) {
		// submit_form
		$j.post($j('form#email_a_friend').attr('url'), $j('form#email_a_friend').serialize());
		dialogWindow.hide();
	}
	
}



/* ----------------------------------------
pzFilter (Prototype)
---------------------------------------- */

var pzFilter = Class.create();
pzFilter.prototype = {
	
	initialize: function(filterElmt, listElmt, options) {
		
		//console.log(filterElmt);
		
		// init pzItemList
		this._pzItemList = pzItemList(listElmt);
		
		// set class variables
		this.filterElmt = $(filterElmt);
		this.listElmt = $(listElmt);
		this.options = Object.extend({
			toggle:'category',
			toggleActive:'category_active',
			content:'options',
			height:null,
			width:320,
			direction:'vertical'
		}, options || {});
		
		// start jquery code fragment
		var max = 10; // default value
		$j('#pzFilter .options').each(function(element){
			var itemLen = $j(this).find('li').length;
			if (max < itemLen) max = itemLen;
		});
		// end jquery code fragment
		
		// init accordian
		this.accordion = new accordion(filterElmt, {
			resizeSpeed: 8,
			classNames: {
				toggle:'category',
				toggleActive:'category_active',
				content:'options'
			},
			defaultSize: {
				height:max*22
			},
			direction:'vertical'
		});
		this.accordion.activate(this.filterElmt.select('.category')[0]);
		
		this.initOptions();
		
		// load selected item
		if (this.filterElmt.down('li.selected')) {
			var url = this.filterElmt.down('li.selected').readAttribute('url');
			this.loadList(url);
		}
		
	},
	
	initOptions: function() {
		// init options
		var options = this.filterElmt.select('li');
		options.each(function(elmt) {
			elmt.observe('click', this.optionClickListener.bind(this));
		}.bind(this));
	},
	
	optionClickListener: function(event) {
		//console.log("optionClickListner");
		var elmt = event.element();
		var url = elmt.readAttribute('url');
		
		if (elmt.up('ul').hasClassName('orientation')) {
			// set selected
			this.setSelected(elmt);
			// load formats
			this.loadFormats(url);
		} else if (elmt.up('ul').hasClassName('format')) {
			// reset siblings
			elmt.siblings().each(function(i) {
				i.removeClassName('selected');
			});
			// set selected
			elmt.addClassName('selected');
			// load list
			this.loadList(url);
		} else {
			// set selected
			this.setSelected(elmt);
			// remove formats
			if (this.filterElmt.select('.format').length > 0) 
				this.filterElmt.select('.format')[0].update('');
			// load list
			this.loadList(url);
		}
		
	},
	
	setSelected: function(elmt) {
		// remove selected
		this.filterElmt.select('.selected').each(function(i) {
			i.removeClassName('selected');
		});
		// set selected
		elmt.addClassName('selected');
	},
	
	loadFormats: function(url) {
		//console.log(this.filterElmt.select('.format') + ':' + url);
		
		new Ajax.Updater(this.filterElmt.select('.format')[0], url, {
			method: 'get',
			onComplete: function() {
				
				// init format options
				var options = this.filterElmt.select('.format li');
				options.each(function(elmt) {
					elmt.observe('click', this.optionClickListener.bind(this));
				}.bind(this));
				
			}.bind(this)
		});
	},
	
	loadList: function(url) {
		this._pzItemList.loadList(url);
	}

};






