var buy_popups = {};

function buy_popup_setup(){

	var gauze = getByClass('buy_float_gauze')[0];
	if (!gauze){
	
		gauze = document.createElement('div');
		gauze.className = 'buy_float_gauze';

		var body = document.getElementsByTagName('body')[0];
		body.appendChild(gauze);
		addtachEvent('resize', function (){ resize_to_screen_height(gauze); });
		resize_to_screen_height(gauze);
	}
}
function activate_buy_popup(ean){
	var popup;
	var gauze = getByClass('buy_float_gauze')[0];

	///////////////////////////////////////////
	// Little Brother HACK FIXME BAD
	///////////////////////////////////////////

	if (ean == 9780739372869){
		document.location = 'http://www.randomhouse.com/audio/littlebrotheraudiobook/';
		return;
	}
	
	///////////////////////////////////////////

	if (!gauze){
		buy_popup_setup();
		gauze = getByClass('buy_float_gauze')[0];
	}
	gauze.style.display = 'block';

	if (buy_popups[ean]){
		popup = buy_popups[ean];
	}
	else{
		var body = document.getElementsByTagName('body')[0];
		buy_popups[ean] = popup = getByID('buy_popup_' + ean);	

		body.appendChild(popup);

		var close = getByClass('buy_float_close', popup)[0];
		var dragbar = getByClass('buy_float_title', popup)[0];

		makeDraggable(dragbar, popup);

		var upButton 			= getByClass('buy_float_ticker_up', popup)[0];
		var downButton 			= getByClass('buy_float_ticker_down', popup)[0];
		var quantDisplay	 	= getByClass('buy_float_quantity_display', popup)[0];
		var quantInput 			= getByClass('buy_float_quantity_input', popup)[0];
		var addToCartButton 	= getByClass('buy_float_add_to_cart', popup)[0];
		var addToCartForm 		= getByClass('buy_float_cart_form', popup)[0];

		addtachEvent('click', function(){
				popup.style.display = 'none';
				gauze.style.display = 'none';
			}, close);
		addtachEvent('mouseover', function(){
				close.className = 'buy_float_close_over';
			}, close);
		addtachEvent('mouseout', function(){
				close.className = 'buy_float_close';
			}, close);

		if (upButton){
			upButton.normalStyle 		= '0px 0px';
			upButton.disabledStyle 		= '11px 0px';
			upButton.activeStyle 		= '22px 0px';
			downButton.normalStyle 		= '0px 7px';
			downButton.disabledStyle 	= '11px 7px';
			downButton.activeStyle 		= '22px 7px';

			downButton.stop = true;

			addtachEvent('mousedown', function(){
					if (buy_float_quant_increment(upButton, quantDisplay, quantInput)){
						upButton.style.backgroundPosition = upButton.activeStyle;
						downButton.style.backgroundPosition = downButton.normalStyle;
						downButton.stop = false;
					}
					else{
						upButton.stop = true;
						upButton.style.backgroundPosition = upButton.disabledStyle;
					}
				}, upButton);
			addtachEvent('mouseup', function(){
					if (! upButton.stop){
						upButton.style.backgroundPosition = upButton.normalStyle;
					}
				}, upButton);
			addtachEvent('mouseout', function(){
					if (! upButton.stop){
						upButton.style.backgroundPosition = upButton.normalStyle;
					}
				}, upButton);

			addtachEvent('mousedown', function(){
					if (buy_float_quant_decrement(downButton, quantDisplay, quantInput)){
						downButton.style.backgroundPosition = downButton.activeStyle;
						upButton.style.backgroundPosition = upButton.normalStyle;
						upButton.stop = false;
					}
					else{
						downButton.stop = true;
						downButton.style.backgroundPosition = downButton.disabledStyle;
					}
				}, downButton);
			addtachEvent('mouseup', function(){
					if (! downButton.stop){
						downButton.style.backgroundPosition = downButton.normalStyle;
					}
				}, downButton);
			addtachEvent('mouseout', function(){
					if (! downButton.stop){
						downButton.style.backgroundPosition = downButton.normalStyle;
					}
				}, downButton);
		}


		if (addToCartButton){
			addtachEvent('click', function(){
					addToCartForm.submit();
				}, addToCartButton);

			addToCartButton.origsrc = addToCartButton.src;
			addToCartButton.oversrc = addToCartButton.src.replace(/(\.[^.]+)$/, '_on$1');
		
			addtachEvent('mouseover', function(){
					addToCartButton.src = addToCartButton.oversrc;
				}, addToCartButton);

			addtachEvent('mouseout', function(){
					addToCartButton.src = addToCartButton.origsrc;
				}, addToCartButton);
		}


		var buy_float_fields = getByClass('buy_float_field', popup);

		if (buy_float_fields[0]){
			for (var i=0; i<buy_float_fields.length; i++){
				buy_float_setup_self_delete(buy_float_fields[i]);
			}

			// pre-order lacks this section
			var googleSearchButton 	= getByClass('buy_float_find_a_store', popup)[0];
			var googleHiddenNear	= getByClass('buy_float_google_near', popup)[0];
			var googleForm			= getByClass('buy_float_google_form', popup)[0];

			addtachEvent('click', function (){
				var city = buy_float_fields[0].value; 
				var state = buy_float_fields[1].value; 
				var zip = buy_float_fields[2].value; 

				if (city == 'City'){
					city = '';
				}
				if (state == 'State'){
					state = '';
				}
				if (zip == 'Zip Code'){
					zip = '';
				}

				
				googleHiddenNear.value = city + ', ' + state + ' ' + zip;
				googleForm.submit();
			}, googleSearchButton);

			addtachEvent('mouseover', function(){
				googleSearchButton.style.backgroundPosition = '0px 20px';
			}, googleSearchButton);
			addtachEvent('mouseout', function(){
				googleSearchButton.style.backgroundPosition = '0px 0px';
			}, googleSearchButton);
		}
			
	}
	center_to_screen(popup);
	popup.style.display = 'block';

	// return false because this will be triggered by an a tag
	return false;
}
function buy_float_setup_self_delete(field){
	// move this into its own function to create new closure

	field.startValue = field.value
	field.startColor = field.style.color;

	addtachEvent('focus', function (){
			if (field.startValue == field.value){
				field.value = '';
				field.style.color = 'black';
			}
		}, field);
	addtachEvent('blur', function (){
			if (field.value == ''){
				field.style.color = field.startColor;
				field.value = field.startValue;
			}
		}, field);
}
function buy_float_quant_increment(button, display, input){
	var max = 99;
	if (input.value >= max){
		return false;
	}
	else if (input.value == (max -1)){
		input.value++;
		display.innerHTML = input.value;
		return false;
	}
	input.value++;
	display.innerHTML = input.value;
	return true;
}
function buy_float_quant_decrement(button, display, input){
	var min = 1;
	if (input.value <= min){
		return false;
	}
	else if (input.value == (min +1)){
		input.value--;
		display.innerHTML = input.value;
		return false;
	}
	input.value--;
	display.innerHTML = input.value;
	return true;
}

/*******************************************************************************
**  general reusable functions
*******************************************************************************/

function center_to_screen(div){
	// can't discover width of an invisible object, so 
	// we have to position it off to the side and make it visible
	div.style.left = '-5000px';
	div.style.display = 'block';

	var s_width;
	var s_height;
	var x_scroll;
	var y_scroll;
	var d_width = div.offsetWidth;
	var d_height = div.offsetHeight;

	if (self.innerHeight) {
		s_width = self.innerWidth;
		s_height = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) {
		s_width = document.documentElement.clientWidth;
		s_height = document.documentElement.clientHeight;
	}
	else if (document.body) {
		s_width = document.body.clientWidth;
		s_height = document.body.clientHeight;
	}

	if (self.pageYOffset) {
		x_scroll = self.pageXOffset;
		y_scroll = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		x_scroll = document.documentElement.scrollLeft;
		y_scroll = document.documentElement.scrollTop;
	}
	else if (document.body) {
		x_scroll = document.body.scrollLeft;
		y_scroll = document.body.scrollTop;
	}

	var left 	= (Math.round(s_width/2) - Math.round(d_width/2) + x_scroll);
	var top 	= (Math.round(s_height/2) - Math.round(d_height/2) + y_scroll);
	
	div.style.left = left + 'px';
	div.style.top = top + 'px';

}
function resize_to_screen_height(div){

	var height, width;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight

	if (test1 > test2) {
		height = document.body.scrollHeight;
		width = document.body.scrollWidth;
	}
	else {
		height = document.body.offsetHeight;
		width = document.body.offsetWidth;
	}

	//alert ('resize to ' + height);

	div.style.height = height + 'px';
	div.style.width = width + 'px';
}

function getByID(ID){
    if (document.getElementById){
        return document.getElementById(ID);
    }
    else if ((document.all) && (eval ('document.all.' + ID))){
        return eval ('document.all.' + ID);
    }
}
function getByClass(cls, top) {
    var elements;
    var elements_list = [];
    var pattern = new RegExp("(^|\\s)"+cls+"(\\s|$)");

    (top) || (top = document);
    elements = top.getElementsByTagName('*')

    for (var i=0; i<elements.length; i++){
        if (pattern.test(elements[i].className)){
            elements_list.push(elements[i]);
        }
    }
    return elements_list;
}
function addtachEvent(evt, daFunction, obj){
    (obj) || (obj = window);
    if (window.addEventListener){
        obj.addEventListener(evt, daFunction, false);
    }
    else if (window.attachEvent){
        obj.attachEvent( "on" + evt, daFunction);
    }
}
function makeDraggable(bar, obj){
	addtachEvent('mousedown', function(event){
		dragDown(bar, obj, event);
	}, bar);
	addtachEvent('mouseup', function(event){
		dragUp(bar, obj, event);
	}, document);
	addtachEvent('mousemove', function(event){
		dragMove(bar, obj, event);
	}, document);
}
function dragDown(bar, obj, evt){
	evt = (evt) ? evt : ((event) ? event :null);
	bar.dragging = 1;

	if (!document.all){
	   bar.startY = evt.screenY;
	   bar.startX = evt.screenX;
	}
	else {
	   bar.startX = evt.clientX;
	   bar.startY = evt.clientY;
	}

	bar.startLeft = extractNumber(obj.style.left);
	bar.startTop = extractNumber(obj.style.top);
}
function dragMove(bar, obj, evt){
	if (bar.dragging){
		evt = (evt) ? evt : ((event) ? event :null);

		var moveX, moveY;
		if (!document.all){
			moveY = evt.screenY - bar.startY;
			moveX = evt.screenX - bar.startX;
		}
		else{
			moveY = evt.clientY - bar.startY;
			moveX = evt.clientX - bar.startX;
		}

		obj.style.left = (bar.startLeft + moveX) + 'px';
		obj.style.top = (bar.startTop + moveY) + 'px';

		// prevent text selection
		document.body.focus();
		document.onselectstart = function () { return false; };
		return false;
	}
}
function dragUp(bar, obj, evt){
	if (bar.dragging){
		evt = (evt) ? evt : ((event) ? event :null);
		bar.dragging = null;
		document.onselectstart = null;
	}
}
function extractNumber(value) {
	var n = parseInt(value);
	return n == null || isNaN(n) ? 0 : n;
}

addtachEvent('load', function (){ buy_popup_setup(); });


