// Functions for getting the next and previous sibling elements
function get_next_sibling_element(CurrentElement)
{
	var next_sibling = CurrentElement.nextSibling;
	
	while(next_sibling && next_sibling.nodeType != 1) 
	{
    next_sibling = next_sibling.nextSibling
	}
	
	return next_sibling;
}

function get_previous_sibling_element(CurrentElement)
{
	var prev_sibling = CurrentElement.previousSibling;
	
	while(prev_sibling && prev_sibling.nodeType != 1) 
	{
    prev_sibling = prev_sibling.previousSibling
	}
	
	return prev_sibling;
}

// Functions for getting the natural height and width (ie. the original height/width) of images (thanks IE and Opera!!)
function get_natural_dimensions(ImgEl)
{
	var natural_img = {height:"", width:""};
	
	// If this is a browser that supports naturalHeight/Width then just use them!
	if(ImgEl.naturalHeight)
	{
		natural_img.height = ImgEl.naturalHeight;
		natural_img.width = ImgEl.naturalWidth;
	}
	// Otherwise we need to work it out (IE...grumble...grumble...grumble!!)
	else
	{
		var temp_img = new Image();
		temp_img.src = ImgEl.src;
		
		while(!temp_img.complete)
		{
		}
		natural_img.height = temp_img.height;
		natural_img.width = temp_img.width;
	}

	return natural_img;	
}

// 
// Functions for scrolling images
//
var MoveInterval = 10;
var IntMovePx = 20;
var FastMovePx = 3000;
var TimerVar;

// Glide Scrolls images to the right on a mouseclick 
// (if just want it to move straight there then uncomment the line of code at the bottom and comment the line above it.
function glide_right(DivId)
{
	div_el = document.getElementById(DivId);
	
	// Only scroll if we haven't reached the end of the scroll box!
	if ((div_el.scrollLeft + div_el.offsetWidth) < div_el.scrollWidth)
	{
		// Loop through all the thumbnails to find the thumbnail where we want to scroll to. 
		for(count = 0; count < div_el.children.length; count++)
		{
			// If this is the first thumbnail on the right that isn't completely displayed then we've found it!
			if(((div_el.children[count].offsetLeft + div_el.children[count].offsetWidth) - div_el.offsetLeft) > 
					(div_el.scrollLeft + div_el.offsetWidth))
			{
				break;
			}
		}
		
		// Scroll to the thumbnail we've found
		move_right(DivId, div_el.children[count].offsetLeft - div_el.offsetLeft);
		//div_el.scrollLeft = (div_el.children[count-1].offsetLeft - div_el.offsetLeft);
	}	
	// If we are at the end of the scroll box we want to go back to the very start
	else
	{
		//move_left(DivId, 0, "T");
		div_el.scrollLeft = 0;
	}
}

// This actially scrolls the images to the right - called by the above function. 
// It recursively calls itself through the timeout function until the correct position is reached.
function move_right(DivId, EndPos, FastFlag)
{
	div_el = document.getElementById(DivId);

  // If we've either reached the position we want to scroll to or scrolled as far as we can then clear the timer to stop scrolling
	if ((div_el.scrollLeft >= EndPos) || (div_el.scrollLeft == (div_el.scrollWidth - div_el.offsetWidth)))
	{
		clearTimeout(TimerVar);
	}
	// Otherwise scroll to the right and call this function again to keep going
	else
	{
		if (FastFlag == "T")
		{
			div_el.scrollLeft += FastMovePx;
		}
		else
		{
			div_el.scrollLeft += IntMovePx;
		}
		TimerVar = setTimeout("move_right('"+DivId+"','"+EndPos+"')", MoveInterval); 
	}
}

// Glide Scrolls images to the left on a mouseclick 
function glide_left(DivId)
{
	div_el = document.getElementById(DivId);
	
	// Only scroll if we haven't reached the start of the scroll box!
	if (div_el.scrollLeft > 0)
	{
		// Loop through all the thumbnails to find the thumbnail we want to scroll to. 
		// Must loop through backwards as we're scrolling from right to left
		for(count = div_el.children.length - 1; count >= 0; count--)
		{
			if((div_el.children[count].offsetLeft - div_el.offsetLeft) < div_el.scrollLeft)
			{
				break;
			}
		}
		
		// Scroll to the thumbnail we've found 
		move_left(DivId, 
						  ((div_el.children[count].offsetLeft + div_el.children[count].offsetWidth) - div_el.offsetLeft) - div_el.offsetWidth);
	}	
	// If we are at the start of the scroll box we want to go back to be at the very end
	else
	{
		//move_right(DivId, div_el.scrollWidth, "T");
		div_el.scrollLeft = div_el.scrollWidth;
	}
}

// This actially scrolls the images to the left - called by the above function. 
// It recursively calls itself through the timeout function until the correct position is reached.
function move_left(DivId, EndPos, FastFlag)
{
	div_el = document.getElementById(DivId);

  // If we've either reached the position we want to scroll to or scrolled as far as we can then clear the timer to stop scrolling
	if ((div_el.scrollLeft <= EndPos) || (div_el.scrollLeft == 0))
	{
		clearTimeout(TimerVar);
	}
	// Otherwise scroll to the left and call this function again to keep going
	else
	{
		if (FastFlag == "T")
		{
			div_el.scrollLeft -= FastMovePx;
		}
		else
		{
			div_el.scrollLeft -= IntMovePx;
		}
		TimerVar = setTimeout("move_left('"+DivId+"','"+EndPos+"')", MoveInterval); 
	}
}

//
// Functions to change the main image
//

function preload_gallery()
{
	var images = new Array();
	
	for (i = 0; i < preload_gallery.arguments.length; i++)
	{
		images[i] = new Image();
		images[i].src = preload_gallery.arguments[i];
	}
}

var CurrentPhotoId;

// Set the current photo id. This is used when the page is first loaded
function set_current_photo(PhotoId, GalleryType)
{
	// If there's a hash tag then take this as the photo id.
	if (window.location.hash) 
	{
			temp_photo_id = window.location.hash.replace('#Id=', '');
			
			// Before we use it though we'll need to make sure there's a photo in the gallery with this id 
			if(document.getElementById(temp_photo_id))
			{
					CurrentPhotoId = temp_photo_id;
			}
	}

	// If we don't have a current photo set yet then use the one passed through
	if (!CurrentPhotoId)
	{
			CurrentPhotoId = PhotoId;
	}

	// Set the gallery type
	gallery_type = GalleryType;

	// Set the current photo
	ChangePhoto(CurrentPhotoId, 'T');
	
	// Go to its thumbnail
	setTimeout(document.getElementById("thumbnails").scrollLeft = current_tn.offsetLeft - document.getElementById("thumbnails").offsetLeft - 400, 1000);
}

// Change the photo/movie etc we're sharing with the addthis toolbox
function create_addthis_toolbox()
{ 
		var addthis_config =
		{
   			ui_click: true,
				ui_header_color: "#666666",
				ui_header_background: "#e6e6e6",
				ui_use_addressbook: true,
				services_expanded: "facebook, email, aolmail, blogger, digg, friendster, gmail, google, hotmail, kindleit, livejournal, linkedin, live, myspace, reddit, stumbleupon, tumblr, twitter, wordpress, yahoomail, mymailru, googlereader, bebo, goodnoows"
		}

		var addthis_share =
		{
   			url: new_page_link,
				title: new_title,			
  			templates: { twitter: "Just beautiful! {{url}} {{title}} from @LTM_LisaFrost" },
				email_vars: { photo_loc: SITE_URL + "/" + new_photo_loc } 
		}
		
		var addthis_html = "<div class='custom_images'>Share on <a class='addthis_button_facebook'><img src='facebook_16.png' /></a><a class='addthis_button_twitter' tw:count='none'><img src='twitter_16.png' /></a><a class='addthis_button_email'><img src='email_16.png' /></a><a class='addthis_button_expanded'><img src='addthis_16.png' /></a></div>";

		document.getElementById("share_btns").innerHTML = addthis_html;
		addthis.toolbox("#share_btns", addthis_config, addthis_share);
}

function replaceQueryString(url,param,value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re))
        return url.replace(re,'$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}

// Change the main photo in a gallery 
function ChangePhoto(NewId, DisplayTitle)
{
		// Temporarily put a "loading" gif to show if while the image is loading.
		// This isn't used if the gallery is either for movies or books
	/*	if ((gallery_type != 'BISP') && (gallery_type != 'MISP') && (gallery_type != 'VLOG'))
		{
				document.getElementById("main_photo").src = "loading.gif";
		}*/
		
		// Get the details of the photo to set
		new_name = document.getElementById(NewId+"_name").innerHTML;
		new_title = document.getElementById(NewId+"_title").innerHTML;
		new_photo_loc = document.getElementById(NewId+"_photo_loc").innerHTML;
		new_page_link = SITE_URL + "/" + document.getElementById(NewId+"_page_link").innerHTML;
		new_description = document.getElementById(NewId+"_description").innerHTML;
		new_message_identifier = document.getElementById(NewId+"_message_identifier").innerHTML;
		
		// Update the url to reflect the current photo so people can bookmark this exact photo
		location.replace("#Id="+NewId);
    
		// Set the image to the new photo
		document.getElementById("main_photo").src = new_photo_loc;

		// Set the link for the Download Image button
		//document.getElementById("download_link").href = new_page_link;

		// Set the link for the slideshow button
		// This isn't used if the gallery is either for movies or books
		if ((gallery_type != 'BISP') && (gallery_type != 'MISP') && (gallery_type != 'VLOG'))
		{
				document.getElementById("slidshow_link").href = "slideshow.php" + GalleryParam + "#Id=" + NewId;
		}

		// Change the name of the image
		if (DisplayTitle == "T")
		{
				document.getElementById("photo_name").innerHTML = new_name;
		}
		
		// Un-highlight the old thumbnail
		old_tn = document.getElementById(CurrentPhotoId);
		old_tn.className = "normal_tn";	
		
		// Highlight the thumbnail that is currently showing.
		current_tn = document.getElementById(NewId);
		current_tn.className = "highlight_tn";	
		
		// Change the description and show the div if there is a description
		if (new_description)
		{
				document.getElementById("description").innerHTML = new_description;
				document.getElementById("description_div").style.display = "block";
		}
		// Otherwise hide the description div
		else
		{
				document.getElementById("description_div").style.display = "none";
		}
		
		// Change the url of the addthis toolbox		
		create_addthis_toolbox();
		
		// Change the url for the facebook comments box by recreating and reinitialising it
		var fb_tag = "<fb:comments href='"+ new_page_link +"' num_posts='5' width='350'></fb:comments>";
		document.getElementById("fb_comments").innerHTML = fb_tag;
				
    window.fbAsyncInit = function() 
		{
      FB.init({appId: '105701913445', 
							 status: true, 
							 cookie: true, 
							 xfbml: true, 
							 oauth: true, 
							 channelUrl: 'http://localhost/LTM/fb_channel.php'});
    };
    (function() {
      var e = document.createElement('script'); e.async = true;
      e.src = document.location.protocol +
        '//connect.facebook.net/en_US/all.js';
      document.getElementById('fb-root').appendChild(e);
    }());
		
		// Loop through the products and update all the images and photo ids to the new photo
		for(count = 1; count <= ProductCount; count++)
		{
				document.getElementById("ProductPhotoLoc"+count).src = 
				document.getElementById("ProductPhotoLoc"+count).name.replace("XXX", new_message_identifier);
				document.getElementById("ProductThumbnailLoc"+count).src = 
				document.getElementById("ProductThumbnailLoc"+count).name.replace("XXX", new_message_identifier);
				document.getElementById("ProductPhotoId"+count).value = NewId;
		}
		
		// Add the id to the url so the current photo can be bookmarked etc
		//var stateObj = NewId;
		//history.replaceState(stateObj, NewTitle, NewPageLink);
		
    // Change the AddThis url and Title
/*		var addThisEl = document.getElementById("main_addthis");
		addThisEl.setAttribute('addthis:url', "http://www.lovethismoment.com/" + new_page_link);
		addThisEl.setAttribute('addthis:title', new_name);
		
		//addthis.update('share', 'url', NewLink);
		//addthis.update('share', 'title', NewTitle);
		addthis.toolbox(addThisEl);
	*/	
	  // Set the variable that holds the id of the current photo
		CurrentPhotoId = NewId;
		
	//natural_img = get_natural_dimensions(document.getElementById("main_photo"));
/*		while(!document.getElementById("main_photo").complete)
		{
		}*/
}

// Move to the next photo in a gallery
function next_photo(DisplayTitle)
{
	// Get the thumbnail element of the photo currently displayed
	current_tn = document.getElementById(CurrentPhotoId);
	
	// Get the div the thumbnails are stored in
	tn_div = document.getElementById("thumbnails");
	
	// Get the next sibling element
	next_sibling = get_next_sibling_element(current_tn);
	
	// If there is no next thumbnail then we'll be going back to the start
	if (!next_sibling)
	{
		next_tn = current_tn.parentNode.children[0].id;
		
		// Scroll back to the first thumbnail
		tn_div.scrollLeft = 0;
	}
	// Otherwise set it to the next thumbnail
	else
	{
		next_tn = next_sibling.id; 
	
		// Scroll the thumbnails so this one is in the middle of the page.
		tn_div.scrollLeft = next_sibling.offsetLeft - tn_div.offsetLeft - 400;
	}
	
	// Change the photo
	ChangePhoto(next_tn, DisplayTitle);
}

// Move to the prev photo in a gallery
function previous_photo(DisplayTitle)
{
	// Get the thumbnail element of the photo currently displayed
	current_tn = document.getElementById(CurrentPhotoId);
	
	// Get the div the thumbnails are stored in
	tn_div = document.getElementById("thumbnails");
	
	// Get the previous thumbnail element
	prev_sibling = get_previous_sibling_element(current_tn);
	
	// If there is no previous thumbnail then we'll be going to the end
	if (!prev_sibling)
	{
			prev_tn = current_tn.parentNode.children[current_tn.parentNode.children.length-1].id;
		
		// Scroll to the last thumbnail
		tn_div.scrollLeft = current_tn.parentNode.children[current_tn.parentNode.children.length-1].offsetLeft - tn_div.offsetLeft;
	}
	// Otherwise set it to the next thumbnail
	else
	{
		prev_tn = prev_sibling.id; 
		
		// Scroll the thumbnails so this one is on the left.
		tn_div.scrollLeft = prev_sibling.offsetLeft - tn_div.offsetLeft - 400;
	}
	
	// Change the photo
	ChangePhoto(prev_tn, DisplayTitle);
}

//
// Functions for running the slideshow
//

var ShowInt;
var PhotoInterval = 4000;

//
// May need to pre-load images
//

// Start the slideshow
function start_slideshow()
{
	// Other than the first time this is called we want to show the next photo soon after the person clicks the play button
	if(ShowInt)
	{
		setTimeout(slideshow_next_photo, 500);
	}
	// The first time this is called we want to go to the photo id given in the hash tag (if there is one)
	else
	{
			// If there's a hash tag then take this as the photo id.
			if (window.location.hash) 
			{
					temp_photo_id = window.location.hash.replace('#Id=', '');
					
					// Before we use it though we'll need to make sure there's a photo in the gallery with this id 
					if(document.getElementById(temp_photo_id))
					{
							first_photo_id = temp_photo_id;
					}
			}
		
			// If we have a valid photo id then go to it
			if (first_photo_id)
			{			
					slideshow_set_photo(first_photo_id);
					CurrentPhotoId = first_photo_id;
			}
	}
	
	// Set the interval so the photo keeps changing to the next photo
	ShowInt = setInterval(slideshow_next_photo, PhotoInterval);
	
	// Change the play button to pause
	document.getElementById("play_text").innerHTML = "Pause";
	document.getElementById("play_btn").href = "javascript:stop_slideshow();";
	document.getElementById("main_photo").title = "Click to Pause";
	document.getElementById("photo_click").href = "javascript:stop_slideshow();";
}

// Stop/Pause the slideshow
function stop_slideshow()
{
	// Clear the interval so the photo stops changing
	clearInterval(ShowInt);
	
	// Change the pause button to play - includes clicking on the photo
	document.getElementById("play_text").innerHTML = "Play";
	document.getElementById("play_btn").href = "javascript:start_slideshow();";
	document.getElementById("main_photo").title = "Click to Play";
	document.getElementById("photo_click").href = "javascript:start_slideshow();";
}

function slideshow_set_photo(PhotoId)
{	
	// Get the details of the photo to set
	new_name = document.getElementById(PhotoId+"_name").innerHTML;
	new_photo_loc = document.getElementById(PhotoId+"_photo_loc").innerHTML;

	// Set the image to the new photo
	document.getElementById("main_photo").src = new_photo_loc;
	
	// Add the current photo id to the exit url so we go back to the photo we're currently viewing
	document.getElementById("exit_link").href = GalleryUrl + GalleryParam + "#Id=" + PhotoId;
	
	// Update the URL to reflect the new id
	location.replace("#Id="+PhotoId);

	// Set the variable that holds the id of the current photo
	CurrentPhotoId = PhotoId;
	
	// We want to run resize_image in case the screen resized and doesn't correctly fit the current image
	resize_image();
}

// Move to the next photo in the slideshow
function slideshow_next_photo()
{
	// Get the thumbnail element of the photo currently displayed
	current_tn = document.getElementById(CurrentPhotoId);
	
	// Get the next photo element
	next_sibling = get_next_sibling_element(current_tn);
	
	// If there is no next thumbnail then we'll be going back to the start
	if (!next_sibling)
	{
		next_tn = current_tn.parentNode.children[0].id;
	}
	// Otherwise set it to the next thumbnail
	else
	{
		next_tn = next_sibling.id; 
	}

	// Set the new image
	slideshow_set_photo(next_tn);
}

// Move to the previous photo in the slideshow
function slideshow_previous_photo()
{
	// Get the thumbnail element of the photo currently displayed
	current_tn = document.getElementById(CurrentPhotoId);
	
	// Get the previous thumbnail element
	prev_sibling = get_previous_sibling_element(current_tn);
	
	// If there is no previous thumbnail then we'll be going to the end
	if (!prev_sibling)
	{
		prev_tn = current_tn.parentNode.children[current_tn.parentNode.children.length-1].id;
	}
	// Otherwise set it to the next thumbnail
	else
	{
		prev_tn = prev_sibling.id; 
	}
	
	// Set the new image
	slideshow_set_photo(prev_tn);
}

// Resizes the height of a photo in the slideshow 
function resize_image()
{
	var vertical_space = 70;
	var horizontal_space = 90;
	
	// Get the photo element.
	photo_el = document.getElementById("main_photo");

  // Get the height and width of the viewport (display area) and the un-scaled height and width of the image
	viewport_height = get_viewport_height() - vertical_space;
	viewport_width = get_viewport_width() - horizontal_space;	
	natural_img = get_natural_dimensions(photo_el);
	
	// Calculate the width to height ratio of both the viewport and the image
	viewport_ratio = viewport_width / viewport_height;
	image_ratio = natural_img.width / natural_img.height;
	
	if (image_ratio > viewport_ratio)
	{
		width = viewport_width;
		height = natural_img.height / (natural_img.width / width);
	}
	else
	{
		height = viewport_height;
		width = natural_img.width / (natural_img.height / height);
	}
		
	if ((width > natural_img.width) || (height > natural_img.height))
	{
		width = natural_img.width;
		height = natural_img.height;
	}
	
	photo_el.width = width;
	photo_el.height = height;
	
/*	// Caclculate the height of the image based on the viewport, leaving some space top and bottom
	img_height = viewport_height - vertical_space;

	// Check that the calculated height isn't bigger than the actual height of the photo. If if it is just use the photo height
	if (img_height > natural_img.height)
	{
	  img_height = natural_img.height;
	}
	
	// Set the height of the image
	photo_el.height = img_height;	

	// Check if the width has scaled. We do this by seeing if the photo is the same width as the containing table cell 
	// If it has we need to make sure they're both in proportion and the photo is still visible.
	if (photo_el.offsetWidth == photo_el.parentNode.offsetWidth)
	{
		img_height = natural_img.height / (natural_img.width / photo_el.offsetWidth);
  	photo_el.height = img_height;	 
	}*/
}


/*
var UpdateInterval = 30;
var PixelPerInterval = 10;
var ScrollerInterval;

function start_scroll_right(DivId) 
{
	ScrollerInterval = setInterval("scroll_right('"+DivId+"')", UpdateInterval);
}

function scroll_right(DivId) 
{
	document.getElementById(DivId).scrollLeft += PixelPerInterval;
}

function start_scroll_left(DivId) 
{
	ScrollerInterval = setInterval("scroll_left('"+DivId+"')", UpdateInterval);
}

function scroll_left(DivId) 
{
	document.getElementById(DivId).scrollLeft -= PixelPerInterval;
}

function stop_scrolling() {
	clearInterval(ScrollerInterval);
}*/


// Functions to get the window size and scroll bar positions
// Needed for support in all browsers
function window_width() 
{
	return filter_results (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function window_height() 
{
	return filter_results (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

function window_scroll_left_pos()
{
	return filter_results (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function window_scroll_top_pos() 
{
	return filter_results (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function filter_results(Win, DocEl, Body) 
{
	var result = Win ? Win : 0;
	
	if (DocEl && (!result || (result > DocEl)))
	{
		result = DocEl;
	}
	
	return Body && (!result || (result > Body)) ? Body : result;
}


// Toggle the "popup" windows on and off
function toggle(DivId) 
{
	var div_el = document.getElementById(DivId);
	
	if ( div_el.style.display == 'none' ) 
	{	
		div_el.style.display = 'block';
	}
	else 
	{
		div_el.style.display = 'none';
	}
}

// Get the height of the viewport of the screen
function get_viewport_height()
{
	if (typeof window.innerHeight != 'undefined') 
	{
		viewport_height = window.innerHeight;
	} 
	else 
	{
		viewport_height = document.documentElement.clientHeight;
	}
	
	return viewport_height;
}

// Get the width of the viewport of the screen
function get_viewport_width()
{
	if (typeof window.innerWidth != 'undefined') 
	{
		viewport_width = window.innerWidth;
	} 
	else 
	{
		viewport_width = document.documentElement.clientWidth;
	}
	
	return viewport_width;
}

// Resize the blanket for underneath the "popup" window to fit over the page
function blanket_size() 
{
	viewportheight = get_viewport_height();
	viewportwidth = get_viewport_width();
	
	// Work out the blanket height
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) 
	{
		blanket_height = viewportheight;
	} 
	else 
	{
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) 
		{
			blanket_height = document.body.parentNode.clientHeight;
		} 
		else 
		{
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	
	// Work out the blanket width
	if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) 
	{
		blanket_width = viewportwidth;
	} 
	else 
	{
		if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) 
		{
			blanket_width = document.body.parentNode.clientWidth;
		} 
		else 
		{
			blanket_width = document.body.parentNode.scrollWidth;
		}
	}
	
	// Set the width and height of the blanket
	var blanket = document.getElementById('blanket');
	blanket.style.height = blanket_height + 'px';
	blanket.style.width = blanket_width + 'px';
}

// Position and resize the "popup" window
function window_pos(DivId, ImgName) 
{	
	var IMG_PADDING = 60;
	var MIN_IMG_PADDING = 60;
	var SCREEN_MARGIN = 50;
	
	var div_el = document.getElementById(DivId);
	var img_el = document.getElementById(ImgName);	
	var natural_img = get_natural_dimensions(img_el);
	var div_width = natural_img.width + (IMG_PADDING * 2);
	var div_height = natural_img.height + (IMG_PADDING * 2);	
	var viewport_height = get_viewport_height();
	var viewport_width = get_viewport_width();
	

	// If the div ends up wider than the screen size minus the margin we want around it then resize the div to fit
	if (div_width > (viewport_width - SCREEN_MARGIN))
	{
		change_ratio = div_width / (viewport_width - SCREEN_MARGIN);
		div_width = viewport_width - SCREEN_MARGIN;
		div_height = div_height / change_ratio;
		//alert("div width " + div_width + " height " + div_height);
	}
	
	// If the div ends up higher than the screen size minus the margin we want around it then resize the div to fit
	if (div_height > (viewport_height - SCREEN_MARGIN))
	{
		change_ratio = div_height / (viewport_height - SCREEN_MARGIN);
		div_height = viewport_height - SCREEN_MARGIN;
		div_width = div_width / change_ratio;
		//alert("div height " + div_height + " width " + div_width);
	}
	
	// Reset the images width and height settings to the natural width and height
	img_el.width = natural_img.width;
	img_el.height = natural_img.height;
	
	// If the image is wider than the div minus the minimum margin then resize the image
	if (img_el.width > (div_width - MIN_IMG_PADDING))
	{
		img_el.width = div_width - MIN_IMG_PADDING;
		img_el.height = natural_img.height / (natural_img.width / img_el.width);
	}
	
	// If the image is higher than the div minus the minimum margin then resize the image
	if (img_el.height > (div_height - MIN_IMG_PADDING))
	{
		img_el.height = div_height - MIN_IMG_PADDING;
		img_el.width = natural_img.width / (natural_img.height / img_el.height);
	}
	
	// Get the scroll position so we show it relative to the current view
	scroll_top_pos = window_scroll_top_pos();
	scroll_left_pos = window_scroll_left_pos();
	
	// Position the div so it's in the middle of the screen
	var left_pos = (viewport_width / 2) - (div_width / 2) + scroll_left_pos;
	var top_pos = (viewport_height / 2) - (div_height / 2) + scroll_top_pos;
	
	// Get the size of the padding to put around the image so it's centered in the div
	var img_padding_height = (div_height - img_el.height) / 2;
	var img_padding_width = (div_width - img_el.width) / 2;
	img_el.style.padding = img_padding_height + 'px ' + img_padding_width + 'px';
	
	// Set the size and position of the div
	div_el.style.width = div_width + 'px';
	div_el.style.height = div_height + 'px';
	div_el.style.left = left_pos + 'px';
	div_el.style.top = top_pos + 'px';
}

// Create a "popup" window
function popup2(DivId, ImgId) 
{		
	toggle('blanket');
	toggle(DivId);	
	
	var div_el = document.getElementById(DivId);
	
	if ( div_el.style.display == 'block' ) 
	{	
		blanket_size();
		window_pos(DivId, ImgId);
	}	
}

// Create a popup window
function popup(MyLink, WindowName, Width, Height)
{	
    if (! window.focus)
    {
        return true;
    }

    var href;

    if (typeof(mylink) == 'string')
    {
        href = MyLink;
    }
    else
    {
        href = MyLink.href;
    }

    window.open(href, "_blank",
      'width=' + Width + ', height=' + Height);

    return false;
}

// Re-submit the cart form
function SubmitCart()
{
			var cartForm = document.getElementById("cart_form");			
			cartForm.action = "cart.php";
			cartForm.submit();			
}

function GoAnchor(Anchor)
{
		window.location='#' + Anchor;
}


//
// Functions for the drop down menus
//

var timeout	= 300;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id)
{	
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose; 
