// MT_MAIN.JS
// Functions for dynamic image sizing, scrolling, etc.

// Variables relating to infinite loop issue
// -----------------------------------------
var resizeCount = 0;
var totalResizeCount = 0;
var myLastWidth = 0;

var contentHeight;
var textPosition = 0;
var reducedScrollHeight = 15; // Reduction in scroll height in px (allow 1 line overlap while scrolling)
textDivTopMargin = 0;
textDivBottomMargin = 15; // bottom margin of scrolling copy in pixels. Must be set here, or scrolling fails

var absoluteMinScreenWidth = 970;  // Minimum acceptable screen width, in px
var imgWidthPercentOfScreen = .55; // Same % as imageDiv width

// Scrolling parameters
// ========================================
var timeouts = new Array; // Store scrolling timeouts in here
var scrolldelayconstant = 2; //was 4
var scrollcoefficient = 2;
var scrollexponent = 4;
	
//if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.indexOf("MSIE 8") > -1) {
//	scrolldelayconstant = 0;
//	scrollcoefficient = 1.2;
//	scrollexponent = 1;
//}


function resize() {

	// Skip if no imageDIV (allocation path pages, etc.)
	if (!document.getElementById("imageDiv")) {
		return;
	}
	var myWidth, myHeight = 0;

	if(!window.innerWidth) { // IE
		if(!(document.documentElement.clientWidth == 0)) {
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else {
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
	} else {
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	if (!myWidth) { myWidth = absoluteMinScreenWidth; }

	// Ham-fisted approach to the possible infinite loop caused by scroll bar bounce
	// Slightly improved by the max_difference test
	// ----------------------------------------------------------------------
	if ((resizeCount > 100 && Math.abs(myWidth-myLastWidth) < 50) || totalResizeCount > 500) {
		return;
	} else if (resizeCount > 100 && Math.abs(myWidth-myLastWidth) >= 50) {
		// If you moved more than 50px, reset the resizeCount
		resizeCount = 0;
	}
	myLastWidth = myWidth; // Save for later comparison
	resizeCount++; // Increment the resize count variables
	totalResizeCount++;


	// Set imgWidth based on the browser window width
	var imgWidth = parseInt(imgWidthPercentOfScreen * myWidth);

	// Now constrain it so it never gets too small
	if (imgWidth < (imgWidthPercentOfScreen*absoluteMinScreenWidth)) {
		imgWidth = (imgWidthPercentOfScreen*absoluteMinScreenWidth); 
	}

	// This is the height the image wants to be based on imgWidth:
	var imgProportionalHeight = parseInt(imgWidth/1.333);

	// Content Height is determined by CSS; copy DIV is 63% of myHeight which is 100% of window.
	contentHeight = document.getElementById('copy').offsetHeight;

	if (imgProportionalHeight <= contentHeight) {
		// This means the image wants to be shorter than contentHeight. 
		// Then you have to widen the image and shift it to the left to some degree
		// so it can fill all of contentHeight.
	
		// Set the height of imageDiv
		document.getElementById('imageDiv').style.height = (contentHeight)+"px";

		// Remove the image width and stretch the image height to fit
		if (document.getElementById('mainImage')) {
			document.getElementById('mainImage').removeAttribute('width');
			document.getElementById('mainImage').height = contentHeight;
		}
		
		// Shift the image slightly to the left.
		// The amount to shift the image left is determined by the difference (abs) of the the width 
		// the image *should* be (contentHeight * 1.333) and the actual width of the image on-screen
		// which is smaller because we are compressing the page width. Then divide by 3 because
		// we want to favor the left side of the image (move 1 px left for every 3 px hidden on the right).
		var imgShift = Math.abs(parseInt(((contentHeight*1.333)-imgWidth)/3));

		if (document.getElementById('mainImage')) {
			document.getElementById('mainImage').style.position = "relative";
			document.getElementById('mainImage').style.left = '-'+(imgShift)+'px';
		}

		// This line does not appear to be necessary?
		//document.getElementById('mainImage').style.marginRight = (imgShift*3)+'px';

			
	} else {

		// Otherwise, image is tall enough or too tall, so follow the width of imageDiv
		// and let the height disappear due to the overflow: hidden property of mainContent.
		if (document.getElementById('mainImage')) {
			document.getElementById('mainImage').style.left = "0px";
			document.getElementById('mainImage').removeAttribute('height');
			document.getElementById('mainImage').width = imgWidth;
		}
		document.getElementById('imageDiv').style.height = contentHeight+"px";
		
	}

	// Upon resize, always set the copy to the top position
	document.getElementById('scrolledText').style.marginTop = "0px";
	textDivTopMargin = 0;
	clear_all_timeouts();
	loadCopy();


	//document.getElementById('debug').innerHTML = "Screen Width: "+myWidth+" / Screen Height: "+myHeight+"<BR>"+"ContentHeight: "+contentHeight+"<BR>"+"Image Width: "+imgWidth+" px<br>Image Proportional Height: "+imgProportionalHeight+" px<br />"+"<br />ResizeCount: "+resizeCount+"<BR>My Last Width: "+myLastWidth+"<BR>ImgShift: "+imgShift+"<BR>Image Ratio: "+imgWidth/contentHeight;

	//document.getElementById('debug').innerHTML = "Screen Width: "+myWidth+" / Screen Height: "+myHeight+"<BR>"+"ContentHeight: "+contentHeight+"<BR>"+"Copy Height: "+copyHeight+" px (content - title and text div padding)<br>Text Scroll Height: "+textScrollHeight+" px<br />"+"<br />ResizeCount: "+resizeCount+"<BR>My Last Width: "+myLastWidth+"<BR>ImgShift: "+imgShift+"<BR>Image Ratio: "+imgWidth/contentHeight;
}

function loadCopy() {
	// copyHeight is contentHeight less height of title DIV + bottom margin of text div

	// Grab the title div height and the margin bottom of text div
	var titleDivHeight = document.getElementById('title').offsetHeight;

	// Set the bottom margin of the text div (this may already be in the stylesheet, but this
	// value overrides and is used to calculate copyHeight
	document.getElementById('text').style.marginBottom = textDivBottomMargin+"px";

	// copyHeight is the content box minus the above
	copyHeight = contentHeight-textDivBottomMargin-titleDivHeight;

	// Set the height of the text div
	document.getElementById('text').style.height = copyHeight+"px";

	// Since you have javascript scrolling, remove the scrollbars from the content divs
	document.getElementById('copy').style.overflow = "hidden";
	document.getElementById('text').style.overflow = "hidden";

	// Position the pageArrowDown div (which contains the pageArrowDown arrow)
	// 34px is arbitrary
	document.getElementById('pageArrowDown').style.marginTop = (copyHeight-34)+"px";

	// Set the overflow property on copy div to hidden (if you have JS you have 
	// MT scrolling, otherwise Safari shows a nonfunctional scrollbar on this div)
	// Default in CSS is "auto" so that non-JS browsers get a working scrollbar
	// and we have progressive enhancement
	document.getElementById('copy').style.overflow = "hidden";

	// Show the scrolledText div
	document.getElementById('scrolledText').style.display = "block";

	// Show the arrows div
	document.getElementById('pageArrows').style.display = "block";

	// Hide the down arrow if the entire copy fits inside copyHeight (less the title and padding)
	textScrollHeight = document.getElementById('text').scrollHeight;

	resetArrows();

}


function pageDownScroll() {


	var textRemainingToScroll = document.getElementById('scrolledText').scrollHeight+textDivTopMargin;
 	if (textRemainingToScroll <= copyHeight) {
		return;
	}
		
	clear_all_timeouts();
	
	// How far will you scroll down?
	// If textRemainingToScroll minus copyHeight (what is currently on-screen) is less than copyHeight,
	// scroll (textRemainingToScroll-copyHeight)

	if (textRemainingToScroll-copyHeight < copyHeight) {
		newTextDivTopMargin = textDivTopMargin-(textRemainingToScroll-copyHeight);
	} else {
		// Go a full page
		newTextDivTopMargin = textDivTopMargin-(copyHeight-reducedScrollHeight);
	}

	var scrolldelay = 0;
 	var counter = 0;
	for (i=textDivTopMargin; i>newTextDivTopMargin; i--) {
		percentageScrolled = counter/(Math.abs(newTextDivTopMargin-textDivTopMargin));
		counter++;
		//scrollIt = setTimeout("document.getElementById('scrolledText').style.marginTop = ("+i+")+'px'",scrolldelay);
		timeouts[timeouts.length] = setTimeout("document.getElementById('scrolledText').style.marginTop = ("+i+")+'px'",scrolldelay);
		scrolldelay = (scrolldelayconstant+scrolldelay+(Math.pow(scrollcoefficient*(percentageScrolled),scrollexponent)));
	}


	textDivTopMargin = newTextDivTopMargin;


	resetArrows();
}



function pageUpScroll() {

	// How far will you scroll up?
	newTextDivTopMargin = textDivTopMargin+(copyHeight-reducedScrollHeight);

	if (textDivTopMargin >= 0) { return; }

	clear_all_timeouts();

	if (newTextDivTopMargin > (-1*reducedScrollHeight)) {
		newTextDivTopMargin = 0;
	}

	var scrolldelay = 0;
	var counter = 0;
	for (i=textDivTopMargin; i<newTextDivTopMargin; i++) {
		percentageScrolled = counter/(Math.abs(newTextDivTopMargin-textDivTopMargin));
		counter++;
		//scrollIt = setTimeout("document.getElementById('scrolledText').style.marginTop = ("+i+")+'px'",scrolldelay);
		timeouts[timeouts.length] = setTimeout("document.getElementById('scrolledText').style.marginTop = ("+i+")+'px'",scrolldelay);
		scrolldelay = (scrolldelayconstant+scrolldelay+(Math.pow(scrollcoefficient*(percentageScrolled),scrollexponent)));
	}


	textDivTopMargin = newTextDivTopMargin;

	resetArrows();

}


function resetArrows() {

	// Show up arrow unless textDivTopMargin is zero or greater

	if (textDivTopMargin >=0) {
		document.getElementById('pageArrowUp').innerHTML = '<img id="pageArrowUpImg" src="images/pageArrowTransparent.gif" width=18 height=16>';
	} else {
		document.getElementById('pageArrowUp').innerHTML = '<a class=hand onclick="javascript:pageUpScroll();"><img id="pageArrowUpImg" src="images/pageArrowUp.gif" width=18 height=16></a>';
	}

	// Show down arrow unless text remaining to scroll is less than copyHeight.
	// textRemainingToScroll is defined as the height of the scrolledText div plus the (zero or negative value)
	// textDivTopMargin. We add 4 px to copyHeight so that if a line ends just at the bottom, we don't see
	// a down arrow (which scrolls to a totally blank page)

	var textRemainingToScroll = document.getElementById('scrolledText').scrollHeight+textDivTopMargin;
 	if (textRemainingToScroll <= copyHeight+4) {
		document.getElementById('pageArrowDown').innerHTML = '<img id="pageArrowDownImg" src="images/pageArrowTransparent.gif" width=18 height=16>';
	} else {
		document.getElementById('pageArrowDown').innerHTML = '<a class=hand onclick="javascript:pageDownScroll();"><img id="pageArrowDownImg" src="images/pageArrowDown.gif" width=18 height=16></a>';
	}
}

function clear_all_timeouts() {
	if (timeouts) {
		for (var i in timeouts) {
			if (timeouts[i]) {
				clearTimeout(timeouts[i]);
			}
		}
	}
	timeouts = [];
}


function preload_index() {

	// EDIT THE PATH AS NEEDED
	var image_path = "images/site_images/";

	image_objects = new Array();
	images = new Array();

	// EDIT THE IMAGE NAMES AS NEEDED

	images.push(image_path+"../main_nav.gif");

	images.push(image_path+"story.jpg");
	images.push(image_path+"story_bg.jpg");

	images.push(image_path+"mm.jpg");

	images.push(image_path+"vineyard.jpg");

	images.push(image_path+"cor_leonis.jpg");

	images.push(image_path+"experience.jpg");

	images.push(image_path+"mailing_list.jpg");

	images.push(image_path+"contact.jpg");
	images.push(image_path+"press_trade.jpg");

	// Special image path for print logo
	images.push(image_path+"../logo_white.gif");


     for(var i=0; i<images.length; i++) {
		image_objects[i] = new Image();
		image_objects[i].src = images[i];
	}
} 

function preload_story() {
	// EDIT THE PATH AS NEEDED
	var image_path = "images/site_images/";

	image_objects = new Array();
	images = new Array();

	// EDIT THE IMAGE NAMES AS NEEDED
	images.push(image_path+"philosophy.jpg");
     for(var i=0; i<images.length; i++) {
		image_objects[i] = new Image();
		image_objects[i].src = images[i];
	}
}

function preload_people() {
	// EDIT THE PATH AS NEEDED
	var image_path = "images/site_images/";

	image_objects = new Array();
	images = new Array();

	// EDIT THE IMAGE NAMES AS NEEDED
	images.push(image_path+"../subnav_people.gif");
	images.push(image_path+"lt.jpg");
	images.push(image_path+"mat.jpg");
	images.push(image_path+"pm.jpg");

     for(var i=0; i<images.length; i++) {
		image_objects[i] = new Image();
		image_objects[i].src = images[i];
	}
}

function preload_wines() {
	// EDIT THE PATH AS NEEDED
	var image_path = "images/site_images/";

	image_objects = new Array();
	images = new Array();

	// EDIT THE IMAGE NAMES AS NEEDED
	images.push(image_path+"../subnav_wine.gif");
	images.push(image_path+"cabernet.jpg");
	images.push(image_path+"chardonnay.jpg");
	images.push(image_path+"howell_mountain.jpg");
	images.push(image_path+"accolades.jpg");
	images.push(image_path+"wine_lists.jpg");

     for(var i=0; i<images.length; i++) {
		image_objects[i] = new Image();
		image_objects[i].src = images[i];
	}
}

function preload_experience() {
	// EDIT THE PATH AS NEEDED
	var image_path = "images/site_images/";

	image_objects = new Array();
	images = new Array();

	// EDIT THE IMAGE NAMES AS NEEDED
	images.push(image_path+"../subnav_experience.gif");
	images.push(image_path+"wine_tasting.jpg");
	images.push(image_path+"events.jpg");
	images.push(image_path+"map_directions.jpg");

     for(var i=0; i<images.length; i++) {
		image_objects[i] = new Image();
		image_objects[i].src = images[i];
	}
}


