Event.observe(window, 'load', init, false);

PeriodicalExecuter.prototype.registerCallback = function() {
	this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
};

PeriodicalExecuter.prototype.stop = function() {
	clearInterval(this.intervalID);
};

var scroller = null;
var scrollerListWidth = 0;
var scrollerDivWidth = 0;

function init() {
	document.body.oncontextmenu = 'return false;';
	
	if($('previous-link')) {
		Event.observe('previous-link', 'mouseover', function(){ startScroller(3); });
		Event.observe('previous-link', 'mouseout', stopScroller);
	}
	
	if($('next-link')) {
		Event.observe('next-link', 'mouseover', function(){ startScroller(-3); });
		Event.observe('next-link', 'mouseout', stopScroller);
	}

	if($('apply-promo')) {
		Event.observe('apply-promo', 'click', function() {
			updateBag();
			return false;
		});
	}
	
	if($('scroller')) {
		// calculate width of all list items
		var items = $('thumbs-list').select('li');
		for(var i = 0; i < items.length; i++) {
			scrollerListWidth += items[i].getWidth();
		}
		scrollerDivWidth = $('thumbs').clientWidth;
		scrollerDivWidth += -4*items.length; // some were being cut off
	}
	
	if($('info')) {
		
	
	}

	if($('billing')) {
		Validation.add('credit-card', 'This must be a valid credit card number without any hyphens.', {
				 minLength : 13, // value must be at least 6 characters
				 maxLength : 16, // value must be no longer than 13 characters
				 include : ['validate-digits'] // also tests each validator included in this array of validator keys (there are no sanity checks so beware infinite loops!)
		});
		Validation.add('validate-state', 'A state must be selected if the country is set to United States.', function(v) {
			alert(v);
			return false;
		});
		new Validation('shopping-bag');
		if(!$('error')) {
			Element.hide('billing');
			$('place_order').disabled = true;
		}
	}
}

function startScroller(dir) {	
	scroller = new PeriodicalExecuter(function(){ moveIt(dir); }, 0.01);	
}

function moveIt(dir) {
	var thumbs = $('thumbs-list');
	var left = thumbs.style.marginLeft;
	left = left != '' ? parseInt(left) : 0;
	var newLeft = left + dir;
	if(newLeft <= 0 && newLeft >= scrollerDivWidth - scrollerListWidth) {
		thumbs.setStyle({marginLeft: newLeft+'px'}); 
	} 
}

function stopScroller() {
	scroller.stop();
}

function changePress(url) {
	new Ajax.Request(url+'?ajax', {
		method: 'get',
		onSuccess: function(response) {
			var response = unserialize(response.responseText);
			$('press-name').innerHTML = response['name']; 
			$('press-text').innerHTML = response['text']; 
			$('press-image').src = '/images/press/'+response['image']; 
			$('press-enlarge').href = '/images/press/full_'+response['image'];
			document.title = response['name']+' | Dean Harris';
		}
	});
}

function changeItem(url) {
	new Ajax.Request(url+'?ajax', {
		method: 'get',
		onSuccess: function(response) {
			var response = unserialize(response.responseText);

			$('item-name').innerHTML = response['name']; 
			$('item-description').innerHTML = response['description']; 
			$('item-price').innerHTML = response['price'];
			$('item-sale').innerHTML = response['sale_price'];

			//U1 - Added sales price
			if (response['sale_price'] == '$0.00') {
				$('sale-value').hide();
			} else {
				$('sale-value').show();
			}
			
			var itemImage = $('item-image');
			itemImage.src = '/images/shop/full_'+response['image1'];
			if(response['image1_full'] == '') {
				$('image-wrapper').href = '#';
				MagicZoom.stop($('image-wrapper'));
			} else {
				$('image-wrapper').href = '/images/shop/full_'+response['image1_full'];
				MagicZoom.start($('image-wrapper'));
			}

			$('item-add').href = '/shop/bag/?add='+response['id'];
			$('item-remove').href = '/shop/bag/?remove='+response['id'];

			if(response['in_bag'] == 'true') {
				$('item-add').hide(); $('item-remove').show();
			} else {
				$('item-add').show(); $('item-remove').hide();
			}

			for(var i=1; i <= 3; i++) {
				var image = $('image'+i+'-thumb');
				if(image) {
					var li = image.parentNode.parentNode;
					if(response['image'+i] == '') li.style.visibility = 'hidden'; else li.style.visibility = 'visible';
					image.src = '/images/shop/thumb_'+response['image'+i];
					if(response['image'+i+'_full'] != null && response['image'+i+'_full'] != '') {
						image.parentNode.href = '/images/shop/full_'+response['image'+i+'_full'];
					} else {
						image.parentNode.href = '#';
					}
				}
			}
			
			MagicZoom.refresh();
		}
	});
}

function changeItemImage(el) {
	var image = $('item-image');
	image.src = el.childNodes[0].src.replace(/thumb_/, 'full_');
	$('image-wrapper').href = el.href;
	if(el.href.indexOf('#') >= 0)
		MagicZoom.stop($('image-wrapper'));
	else
		MagicZoom.start($('image-wrapper'));
}

function addToBag(url) {
	var total = $('bag-total');
	total.innerHTML = 'Adding...';
	new Ajax.Updater('bag-total', url+'&ajax');
	$('item-add').hide(); $('item-remove').show();
}

function removeFromBag(url) {
	var total = $('bag-total');
	total.innerHTML = 'Removing...';
	new Ajax.Updater('bag-total', url+'&ajax');
	$('item-remove').hide(); $('item-add').show();	
}

function getStores(url) {
	new Ajax.Updater('stores', url+'?ajax');	
}

function changeState(state) {
	var tax = $$('.tax');
	for(var i = 0; i < tax.length; i++) {
		state == 'NY' ? Element.show(tax[i]) : Element.hide(tax[i]);
	}
	state == 'NY' ? Element.hide('no-tax') : Element.show('no-tax');
}

function checkOut() {
	var form = $('shopping-bag');
	var qtys_bag		= document.getElementsByClassName('qty_bag');
	var qtys_paypal = document.getElementsByClassName('qty_paypal');
	for(var i = 0; i<qtys_bag.length; i++) {
		qtys_paypal[i].value = qtys_bag[i].value;
	}
	window.location = '/shop/thanks/';
}

function updateBag() {
	var form = $('shopping-bag');
	form.action = '/shop/bag/';
	form.target = '_self';
	form.submit();
}

//really not important (the first two should be small for Opera's sake)
PositionX = 10;
PositionY = 10;
defaultWidth	= 600;
defaultHeight = 400;

//kinda important
var AutoClose = true;

//don't touch
function popImage(imageURL,imageTitle){
	var imgWin = window.open('','_blank','scrollbars=1,resizable=1,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY);
	if( !imgWin ) { return true; } //popup blockers should not cause errors
	imgWin.document.write('<html><head><title>'+imageTitle+'<\/title><script type="text\/javascript">\n'+
		'function resizeWinTo() {\n'+
		'if( !document.images.length ) { document.images[0] = document.layers[0].images[0]; }'+
		'var oH = document.images[0].height, oW = document.images[0].width;\n'+
		'if( !oH || window.doneAlready ) { return; }\n'+ //in case images are disabled
		'window.doneAlready = true;\n'+ //for Safari and Opera
		'var x = window; x.resizeTo( oW + 200, oH + 200 );\n'+
		'var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;\n'+
		'if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }\n'+
		'else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }\n'+
		'else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }\n'+
		'if( window.opera && !document.childNodes ) { myW += 16; }\n'+
		'x.resizeTo( oW = oW + ( ( oW + 200 ) - myW ), oH = oH + ( (oH + 200 ) - myH ) );\n'+
		'var scW = screen.availWidth ? screen.availWidth : screen.width;\n'+
		'var scH = screen.availHeight ? screen.availHeight : screen.height;\n'+
		'if( !window.opera ) { x.moveTo(Math.round((scW-oW)/2),Math.round((scH-oH)/2)); }\n'+
		'}\n'+
		'<\/script>'+
		'<\/head><body onload="resizeWinTo();"'+(AutoClose?' onblur="self.close();"':'')+'>'+
		(document.layers?('<layer left="0" top="0">'):('<div style="position:absolute;left:0px;top:0px;display:table;">'))+
		'<img src="'+imageURL+'" alt="Loading image ..." title="" onload="resizeWinTo();">'+
		(document.layers?'<\/layer>':'<\/div>')+'<\/body><\/html>');
	imgWin.document.close();
	if( imgWin.focus ) { imgWin.focus(); }
	return false;
}
