// product.js
// loads product details specific JS
// if there's time, work up a way to store which div IDs and links to monitor

function hideOtherProductNav (obj) {
	$$('#product_nav a').each ( function z(n) {
		
		if (n.href == obj.href) {
		} else {
			pNavDeselect(n.up('li'));
		}
	});
}

function hideBoxes () {
	$('description', 'ratings', 'related', 'shipping').invoke('hide');
}

function doNothing(e) {
	Event.stop(e)
}

function pNavDeselect (objLI) {
	objLI.style.padding = "0";
	objLI.style.border = "none";
	objLI.style.textAlign = "center";
	objLI.style.marginRight = "6px";
	objLI.style.height = "30px";
	objLI.style.overflow = "hidden";
	objLI.style.position = "relative";
		
		
	// link
	var objA = objLI.down('a');
		
	objA.style.color = "#333";
	objA.style.textDecoration = "none";
	objA.style.width = "160px";
	objA.style.height = "30px";
	objA.style.backgroundPosition = "top center";
	objA.style.backgroundImage = "url(/images/p_nav_gradient.png)";
	objA.style.backgroundRepeat = "no-repeat";
	objA.style.display = "block";
	objA.style.lineHeight = "30px";
	objA.style.cursor = "pointer";
	objA.stopObserving();
	if (objA.id != 'shippingDetails') {
	    objA.observe ('click', pNavSelect);
    }
	
}

function pNavSelect (e) {
	var obj = Event.element(e);
	
	
	Event.stop(e);
	showLink (obj);
	hideOtherProductNav (obj);
	obj.blur();
	obj.style.cursor = "default";
	obj.stopObserving();
	obj.observe('click', doNothing);
	
	var newBox = $(parseLocation(obj.href));	
	hideBoxes ();
	showBox (newBox);
	
}

function setUpTabBox() {
	$('description', 'ratings', 'related', 'shipping').each ( function hidem(p) {
	    p.style.padding = "16px 25px";
	    p.style.border = "1px solid #d3d3d3";
	    p.style.marginTop = "0";
	    p.hide();
	    //p.style.width = "713px";
    });	
}

function setUpTabNavigation() {
	// add a check to look for # in the URL to see if we need to select a nav tab	
	$('product_nav').style.marginLeft = "30px";
    
	$$('#product_nav li').each ( function z(obj) {
		pNavDeselect(obj);
		//if (obj.down('a').id != 'shippingDetails') {
		obj.down('a').observe('click', pNavSelect);
	    //}
	});
	
	// hides the header
	$('product_nav').firstDescendant().hide();
}

function parseLocation(locstring) {
	var searchstr = locstring.split('#');
	
	if (searchstr.length > 1) {
		if (['description', 'related', 'ratings', 'shipping'].indexOf(searchstr[1]) >= 0) {
		    // if we need query strings we can filter them out here
		    return searchstr[1];
        } else {
	        return 'description';
        }
	} else {
		return 'description';
	}
}

function findLink(locStr) {	
	var returnLink = $('product_nav').down('a');
	$$('#product_nav a').each ( function decide(x) {
		var splithref = x.href.split('#');
		var splitloc = locStr.split('#');
		if ((splithref.length > 1) && (splitloc.length > 1)) {
		    if (splithref[1] == splitloc[1]) {
			    returnLink = x;
		    }
	    }
	});
	return returnLink;
}

function showBox(divObj) {
	hideBoxes();
	divObj.show();	
}

function showLink(linkObj) {
	linkObj.style.backgroundImage = "url(/images/p_nav_grey.png)";
	linkObj.up().style.overflow = "visible";
	linkObj.style.height = "31px";
	linkObj.style.marginBottom = "-1px";	
	linkObj.style.position = "relative";
	linkObj.style.zIndex = "11";
}


function expeditePopup(e) {
    window.open('/fast_ship_items.html?expedite=true', '_blank', 'scrollbars=no,height=400,width=600,titlebar=no,resizeable=no,top=100,left=100,status=no,menubar=no');
    Event.stop(e);
}

function shippingPopup(e) {
    window.open('/shipping_pop.html', '_blank', 'scrollbars=yes,height=600,width=600,titlebar=no,resizeable=no,top=100,left=100,status=no,menubar=no');
    Event.stop(e);
}

function shippingDelivery(e) {
	window.open('/shipping_delivery.html', '_blank', 'scrollbars=yes,height=600,width=600,titlebar=no,resizeable=no,top=100,left=100,status=no,menubar=no');
	Event.stop(e);
}

function imagePopup(e) {
	window.open(e.findElement('a').href, '_blank', 'scrollbars=yes,height=800,width=800,titlebar=no,resizeable=no,top=100,left=100,status=no,menubar=no'); 
	Event.stop(e);
}

function viewReviews(e) {
	Event.element(e).blur();

	var theObj = $('readReviews');	
	
	showLink (theObj);
	hideOtherProductNav (theObj);
	theObj.style.cursor = "default";
	theObj.stopObserving();
	theObj.observe('click', doNothing);
	hideBoxes();
	showBox ($('ratings'));
	theObj.scrollTo();

	Event.stop(e);
}

/* zoom */

function calcOffset () {
	// doing the math over is simpler than binding the inital calcuation to the observers	
	return Math.floor((440 - $('ProdImage').width) / 2);
}


function loadZoomBox () {
	// create yet another div with the original image inside and move it to where the mouse pointer is
	var zoomBox = new Element ('div', {
		style : 'position:relative;z-index:3;overflow:hidden;display:none;',
		id : 'zoomBox'
	});
	zoomBox.style.backgroundColor = "#ffd427";
	zoomBox.style.backgroundPosition = "0px 0px"; // this can be set to some mathematically involved process
	zoomBox.style.backgroundRepeat = 'repeat';
	zoomBox.style.top = "-353px";
	zoomBox.style.left = "0px";
	
	//$('image_container').insert (zoomBox);
}	


function loadZoomImageTest(e) {
	alert (Event.element(e).id);
	Event.stop(e);
}

function loadZoomImage (e) {
	
	// this isn't the ideal solution for stopping the link follow
	
	if ($('zoomBox') == null) {
		//$('ProdImage').stopObserving();
		$('popupLink').blur();
		$('ProdImage').blur();
		clearZoomBox();
		
			
		// pre loading warning
		var loadingImage = new Element ('img', {
			src : '/images/small_loading.gif',
			'style' : 'margin-top:150px',
			id : 'loadingImage'
		});
		$('productZoom').insert (loadingImage); 
	    
	    // use ajax request to determine size of the image
	    // separate the name of the image out
	    var nameSplit = $('ProdImage').src.split('p200/');
	    var xPointer = Event.pointerX(e);
	    var yPointer = Event.pointerY(e);
	    
	    // check to see if its a reload (pointer will be too close to the edge)
	    var ImgOffsets = $("ProdImage").viewportOffset();
	    var WinOffsets = document.viewport.getScrollOffsets();
	    
	    ImgOffsets['left'] = ImgOffsets['left'] + WinOffsets['left'];
	    ImgOffsets['top'] = ImgOffsets['top'] + WinOffsets['top'];
	    
	    // center the alpha box
		if (e.type == 'mouseover') {
		    xPointer = ImgOffsets['left'] + ($('ProdImage').width/2);
		    yPointer = ImgOffsets['top'] + ($('ProdImage').height/2);
	    }
	    
	    new Ajax.Request ('product_image_handler.php', {
		    method: 'post',
		    parameters: 'image_name=' + nameSplit[1],
		    onSuccess: function (response) {
			    //alert (response.headerJSON);
			    
			    if (response.headerJSON) {
				    // validate the header
				    //alert (response.headerJSON);
				    if ((response.headerJSON[0] > 0) && (response.headerJSON[1] > 0) && (response.headerJSON[2].length)) {
						    
					    // preload / load image
					    var scalingFactor = response.headerJSON[3];
					    var preloadImage = new Element ('img', {
						    id : 'zoomImage'
					    });
					    // gets directory from AJAX request
					    preloadImage.src = $('ProdImage').src.replace('p200/', response.headerJSON[2]);
					    var scaledWidth = response.headerJSON[0] * scalingFactor;
					    var scaledHeight = response.headerJSON[1] * scalingFactor;
				        preloadImage.width = scaledWidth;
		                preloadImage.height = scaledHeight;
		                $('loadingImage').remove();
		                
		                // calculate the where to scroll the image to
		                // start reference point
		                
		                var xImg = ImgOffsets['left'];
		                var yImg = ImgOffsets['top'];
		                
		                
		                $('productZoom').insert (preloadImage);
		                
		                createAlphaBox (xPointer, yPointer);
		                
		                   
				        adjustZoomImage (xPointer, yPointer, xImg, yImg, scaledHeight, scaledWidth, scalingFactor);
				        
				        // if you change source that resets pixel dimensions in IE
				        
			        	// draggables
						
						//$('zoomBox').style.position = "relative";
						new Draggable ('zoomBox', {starteffect: false, endeffect: false, 
						    snap: function (x, y, draggable) {
							
						    var theDrag = draggable.element;
						    
						    //var BoxDim = theDrag.viewportOffset();
						    var ImgDim = $('ProdImage').viewportOffset();
						    var WinDim = document.viewport.getScrollOffsets();
						    ImgDim['left'] = ImgDim['left'] + WinDim['left'];
						    ImgDim['top'] = ImgDim['top'] + WinDim['top'];
						    
						    if (x < ImgDim['left']) {
							    var xReturn = ImgDim['left'];
						    } else if (x + theDrag.getWidth() > ImgDim['left'] + $('ProdImage').width) {
							    var xReturn = ImgDim['left'] + $('ProdImage').width - theDrag.getWidth();
						    } else {
							    var xReturn = x;
						    }
						    
						    if (y < ImgDim['top']) {
							    var yReturn = ImgDim['top'];
						    } else if (y + theDrag.getHeight() > ImgDim['top'] + $('ProdImage').height) {
							    var yReturn = ImgDim['top'] + $('ProdImage').height - theDrag.getHeight();
						    } else {
							    var yReturn = y;
						    }
						    
						    return [xReturn, yReturn];	
						    				
						}});
						
						
						Draggables.addObserver ({
							onStart: function (eventName, draggable, event) {
								var WinDim = document.viewport.getScrollOffsets();
								
								zoomController.xRatio = $('zoomImage').getWidth()/$('ProdImage').width;
								zoomController.yRatio = $('zoomImage').getHeight()/$('ProdImage').height;
								zoomController.xLoc = Event.pointerX(event) - WinDim['left'];
								zoomController.yLoc = Event.pointerY(event) - WinDim['top'];
								zoomController.pixelX = $('zoomImage').style.left.replace("px", "");
								zoomController.pixelY = $('zoomImage').style.top.replace("px", "");
								$('ProdImage').stopObserving('mouseout');
								if ($('zoomBox') != null) {
								    $('zoomBox').stopObserving('mouseout');
							    }
						    },
						    element: 'zoomBox'
					    });
					    
					    Draggables.addObserver ({				    
						    onDrag: function (eventName, draggable, event) {
							    
							    var theDrag = draggable.element;
							    
							    var BoxDim = theDrag.viewportOffset();
							    var WinDim = document.viewport.getScrollOffsets();
							    var ImgDim = $('ProdImage').viewportOffset();
							    
							    var xLoc = Event.pointerX(event) - WinDim['left'];
							    var yLoc = Event.pointerY(event) - WinDim['top'];
							    
							    if ((BoxDim['left'] > ImgDim['left']) && (BoxDim['left']+theDrag.getWidth() < ImgDim['left']+$('ProdImage').width)) {
								    var diffX = xLoc - zoomController.xLoc;
								    var moveX = Math.round(zoomController.pixelX - (diffX * zoomController.xRatio));
								    $('zoomImage').style.left = moveX  + "px";
								    zoomController.pixelX = moveX;
								    zoomController.xLoc = xLoc;
							    }
							    
							    if ((BoxDim['top'] > ImgDim['top']) && (BoxDim['top']+theDrag.getHeight() < ImgDim['top']+$('ProdImage').height)) {
								    var diffY = yLoc - zoomController.yLoc;
								    var moveY = Math.round(zoomController.pixelY - (diffY * zoomController.yRatio));
								    $('zoomImage').style.top = moveY + "px";
								    zoomController.pixelY = moveY;
								    zoomController.yLoc = yLoc;
							    }
								
						    },
						    element: 'zoomBox'
						});
						
						Draggables.addObserver ({
						    onEnd: function (eventName, draggable, event) {
							    var ImgDim = $('ProdImage').viewportOffset();
							    var WinDim = document.viewport.getScrollOffsets();
							    
							    var xLoc = Event.pointerX(event) - WinDim['left'];
							    var yLoc = Event.pointerY(event) - WinDim['top'];
							    
							    if ((xLoc < ImgDim['left']) || (xLoc > ImgDim['left'] + $('ProdImage').width) || (yLoc < ImgDim['top']) || (yLoc > ImgDim['top'] + $('ProdImage').height)) {
									if ($('zoomBox') != null) {
								        $('zoomBox').remove();
							        }
									zoomDisable();
									/* disabling mouseover to re-enable zoom
									$('ProdImage').observe ('mouseover', loadZoomImage);
									*/
							    } else {
							        $('ProdImage').observe ('mouseout', hideZoom);
						            $('zoomBox').observe ('mouseout', hideZoom);					            
					            }
					            /* do NOT delete, handy for garbage collection checks
					            alert ("drags: " + Draggables.drags.length);
					            alert ("obs: " + Draggables.observers.length);
					            */
						    },
						    element: 'zoomBox'
					    });
					    
					   $('ProdImage').observe ('mouseout', hideZoom);
					   $('zoomBox').observe ('mouseout', hideZoom);
				   } else {
					   alert ('failed json request: ' + response.headerJSON[0] + " " + response.headerJSON[1] + " " + response.headerJSON[2] + "\n" + response.headerJSON);
				   }
					   
				} else {
				    //alert ('nope');
			    }
			    
		    }
	    });
	    
	    zoomEnable();
		if (Event.element(e).id == 'ProdImage') {
			Event.stop(e);
		}
	} else {
		$('ProdImage').blur();
		$('popupLink').blur();
		Event.stop(e);
	}
}


// should look at queueing options for these 
function zoomEnable () {
	
	new Effect.Morph ('productZoom', {
		style : "border:1px solid #222",
		duration : 0.3
	});
    
    new Effect.Morph ('productZoom', {
	    style : "width:415px",
	    duration : 0.3
    });
    
    //$('product_details').fade({ duration: 0.3 });
    $('detail_overlay').appear ({ duration: 0.3 });
    
}

function zoomDisable () {
	// queue management style
	
	// clear the queue
	var queue = Effect.Queues.get ('global');
	queue.each (function (effect) {
		effect.cancel();
	});
	
	
	// grab start values
	var durationFix = Math.round(($('productZoom').getWidth()/415) * 3)/10;
	
	// start the effects
	
	new Effect.Morph ('productZoom', {
		style : "border:1px solid #FFF",
		duration : durationFix
	});

	new Effect.Morph ('productZoom', {
	    style : "width:0px",
	    duration : durationFix
    });
    
    //$('product_details').appear({ duration: (durationFix+0.2) });    
    $('detail_overlay').fade({ duration: (durationFix+0.2) });
    
}

function clearZoomBox () {
	['loadingImage', 'zoomImage', 'loadingText'].each ( function clearem (s) {
		if ($(s)) {
			$($(s)).remove();
		}
	});
	
}

function createAlphaBox (xPos, yPos) {
	// calculate alpha box size and render
	// calculate box size
	
	var zoomBox = new Element ('div', {
		id : 'zoomBox'		
	});
	//alert (zoomBox.getWidth() + "|" + zoomBox.getHeight());
	
	var zbWidth = Math.floor((415/$('zoomImage').width)*$('ProdImage').width);
	//var zbWidth = Math.floor(((440 + calcOffset()) / $('zoomImage').width) * $('ProdImage').width);
	var zbHeight = Math.floor((350/$('zoomImage').height)*$('ProdImage').height);
	//var zbHeight = Math.floor(($('productZoom').getHeight() / $('zoomImage').height) * $('ProdImage').height);
	
	zoomBox.style.position = "absolute";
	zoomBox.style.zIndex = "1000";
	zoomBox.style.height =  zbHeight+ "px";
	zoomBox.style.width =  zbWidth + "px";
	zoomBox.style.border = "1px solid #222";
	zoomBox.style.pointer = "cursor";
	
	// reference the mouse pointer location and use it for the zoom box
	zoomBox.style.top = (yPos-(zbHeight/2)) + "px";
	zoomBox.style.left = (xPos-(zbWidth/2)) + "px";
	
	//alert (xPos + " : " + yPos);
	
	var zoomHandle = new Element ('div', {
		id : 'zoomHandle',
		style : "background-color:#f3e5a5;width:100%;height:100%;cursor:move"
	});
	//629cd8
	zoomHandle.setOpacity (0.2);
	zoomBox.insert (zoomHandle);
	
	$('image_container').insert(zoomBox);	
	
}


function adjustZoomImage (xPointer, yPointer, xImg, yImg, scaledHeight, scaledWidth, scalingFactor) {
	var preloadImage = $('zoomImage');
	var boxWidth = $('zoomBox').getWidth();
	var boxHeight = $('zoomBox').getHeight();
	
	preloadImage.style.position = "relative";
	var xOffset = Math.floor((scaledWidth/$('ProdImage').width) * (xPointer - (boxWidth/2) - xImg));
	var yOffset = Math.floor((scaledHeight/$('ProdImage').height) * (yPointer - (boxHeight/2) - yImg));
	
    preloadImage.style.top = "-" + yOffset + "px";
    preloadImage.style.left = "-" + xOffset + "px";
    
}

function zoomController () {
	this.xLoc = 0;
	this.yLoc = 0;
	this.xRatio = 1;
	this.yRatio = 1;
	this.pixelX = 0;
	this.pixelY = 0;
}

function hideZoom (e) {
	
	
	var mainImg = $('ProdImage').viewportOffset();
	var WinDim = document.viewport.getScrollOffsets();
	
	xLoc = Event.pointerX(e) - WinDim['left'];
	yLoc = Event.pointerY(e) - WinDim['top'];
	
	if (!((xLoc > mainImg['left']) && (xLoc < mainImg['left'] + $('ProdImage').width) && (yLoc > mainImg['top']) && (yLoc < mainImg['top'] + $('ProdImage').height))) {
		$('zoomBox').stopObserving();
		$('ProdImage').stopObserving('mouseout');
		// remove the draggable
		Draggables.drags.each ( function (d) {
			d.destroy();
		});
		Draggables.removeObserver ( 'zoomBox' );
		
		
		// back to the DOM
		$('zoomBox').remove();
		zoomDisable();
		/* disabling mouseover to re enable zoom
		$('ProdImage').observe ('mouseover', loadZoomImage);
		*/
		Event.stop(e);
	}
}

function testAlert (e) {
	alert ('hey now');
}


// thumbs

function ThumbManager (thumbDir, sourceDir) {
	// simple data object for binding
	this.thumbDirectory = thumbDir;
	this.sourceDirectory = sourceDir;
}


var theManager = new ThumbManager ('p50/', 'p200/');

document.observe ('dom:loaded', function loading() {
	
	setUpTabBox();
	setUpTabNavigation();
	
	showBox($(parseLocation(window.location.href)));
	showLink(findLink(window.location.href));
	
	// that takes care of the product nav, now for the pop ups
	
	if ($('expediteItemLink')) {
	  $('expediteItemLink').observe ('click', expeditePopup);
    } 
    
	$('shippingLink').observe ('click', shippingPopup);
	//$('shippingDetails').observe ('click', shippingDelivery);
	
	
		
	
	// reviews tab link observer
	
	$('readReviews').observe ('click', viewReviews);
	
	// zoom
	//var basePos = 480;
	$('detail_overlay').style.height = ($('product_details_box').getHeight() + 20) + "px";
	
	if ($F('productHasZoom') == "true") {
		$('ProdImage').observe ('click', loadZoomImage);
	} else {
	    $('popupLink').observe ('click', imagePopup);
    }
    
	// old way of doing it
    //$('popupLink').observe ('click', imagePopup);
	
	
	
	//$('productZoom').style.marginLeft = (basePos - calcOffset()) + "px";
	//$('image_container').style.width = $('ProdImage').width + "px";
	
	// this is only going to hold the coordinate info
	// functions to be moved off the object
	//var zc = new ZoomController ();  
	
});

