// eppic.js

// include other js files
document.write("<script language='javascript' src='sha1.js'></script>");
document.write("<script language='javascript' src='ajax.js'></script>");
//document.write("<script language='javascript' src='session.js'></script>");
document.write("<script src='./js/prototype.js' type='text/javascript'></script>");
document.write("<script src='./js/scriptaculous.js' type='text/javascript'></script>");
//document.write("<script language='javascript' src='classes.js'></script>");
document.write("<script src='./js/gallery.js' type='text/javascript'></script>");

function PreLoadImages()
{
	img11=new Image();
	img12=new Image();
	img13=new Image();
	img14=new Image();

	img11.src="./img/menu_photographers_hover.gif";
	img12.src="./img/menu_surf_sessions_hover.gif";
	img13.src="./img/menu_surfers_hover.gif";
	img14.src="./img/menu_home_hover.gif";

	img21=new Image();
	img22=new Image();
	img23=new Image();

	img21.src="./img/nbv_menu_news_hover.gif";
	img22.src="./img/nbv_menu_blogs_hover.gif";
	img23.src="./img/nbv_menu_videos_hover.gif";
}

function edit_focus(id)
{
	var obj=document.getElementById(id);
	obj.style.backgroundImage='';
}

function edit_blur(id)
{
	var obj=document.getElementById(id);
	
	// Only put the background image back if there is no text in the edit
	if(obj.value.length == 0)
	{
		obj.style.backgroundImage='url("./img/'+id+'.gif")';
	}
}
/***
function show_thumbs()
{
	g_delay=0;

	var obj=document.getElementById('gallery_thumbs');
	obj.style.display='block';
	Animate('gallery_thumbs',100,0);
}

function hide_thumbs(delay)
{
	if(delay != null)
	{
		g_delay=delay;
	}
	else
	{
		g_delay=0;
	}

	var obj=document.getElementById('gallery_thumbs');
//	obj.style.display='none';
	Animate('gallery_thumbs',0,100);
}
***/
/***
function view_portfolio_image(img,path,width,height,loc,date,desc,id,session_id,session_user,session_user_name,user,self,comments,admin)
{
	var obj=document.getElementById('portfolio_image');
	
	obj.style.marginTop=Math.floor((400-height)/2);	// kludge to make the damn pic centered vertically

	obj.src="img.php?src="+path+img;
	obj.width=width;
	obj.height=height;

	var _loc=document.getElementById('caption_location');
	var _date=document.getElementById('caption_date');
	var _desc=document.getElementById('caption_desc');
	_loc.innerHTML=loc;
	_date.innerHTML=date;
	_desc.innerHTML=desc;

	// If there is a session_user
	if(session_user.length > 0)
	{
		_date.innerHTML+=" - Photo by <a href='view_profile.php?u="+session_user+"'>"+session_user_name+"</a>";
	}

	// Fill in missing info
	if(loc.length == 0)
	{
		_loc.innerHTML="Unknown";
	}
	if(date.length == 0)
	{
		_date.innerHTML="Unknown";
	}

	// Set the caption links
	var _links=document.getElementById('caption_links');
	var str="";
	
	// If admin, add feature link
	if(admin == 1)
	{
		str+="<a href='feature.php?pid="+id+"'>Feature</a> > ";
	}
	
	if(session_id != "")	// if this is a session photo, be able to buy prints or license it
	{
		// *&* TEMP KLUDGE
//		if(self == 'thezonie' || self == 'Branimir' || self == 'jmairs')
//		{
			str+="<a href='purchase.php?sid="+session_id+"&img="+img+"'>Purchase Print</a> > <a href='javascript:todo();'>License Image</a> ><br>";			
//		}
//		else
//		{
//			str+="<a href='javascript:todo();'>Purchase Print</a> > <a href='javascript:todo();'>License Image</a> ><br>";
//		}
		
		if(self != "" && self != user)	// if this is not my portfolio, be able to add it to my portfolio
		{
//			alert(self+" "+user);
			str+="<a href='view_session_image.php?id="+session_id+"&p="+img+"&a'>Add to Portfolio</a> > ";
		}
	}
	str+="<a href='view_image.php?pid="+id+"'>Link</a> > ";
	str+="<a href='share.php?pid="+id+"'>Share</a> ><br>";
	if(self != "")	// if logged in, be able to blog
	{
		str+="<a href='javascript:blog_portfolio_image("+id+");'>Blog</a> > ";
	}
	str+="<a href='portfolio_comments.php?id="+id+"'>Comments ("+comments+")</a> > ";
	if(session_id != "")	// if this is a session photo, see the whole session
	{
		str+="<a href='view_session.php?id="+session_id+"'>View Session</a> >";
	}
	_links.innerHTML=str;	// set the links to str
}
***/
/***
// Blur and Focus opacity constants (0-100)
var blur_opacity=0;	// was 10
var focus_opacity=100;	// was 50
var start_opacity=100;
var opacity_step=20;	// all opacity goals must be a multiple of the step (was 5)
var opacity_timer=10;	// ms (was 35 ... no, 10)
var g_delay=0;

// The id class
function cid(id,opacity/*,timer* /)
{
	this.id=id;
	this.opacity=opacity;
//	this.timer=timer;
}

var ids=new Array();
var timer=null;

//
// The id is the object, and the op is the opacity that we want that object to get to
//
function Animate(id,op,start_op)
{
	// First reset the op
	if(op == 'blur')
	{
		op=blur_opacity;
	}
	else if(op == 'focus')
	{
		op=focus_opacity;
	}
	else if(op == 'super_focus')
	{
		op=100;
	}

	// First, try and find this object in the array and set the goal opacity
	var i=0;
	var found=false;
	for(i=0;i<ids.length;i++)
	{
		if(ids[i].id == id)
		{
			found=true;
			ids[i].opacity=op;
			break;
		}
	}

	// If we didn't find it, then add it
	if(found == false)
	{
		nid=new cid(id,op/*,null* /);
		ids[i]=nid;
//		document.getElementById(id).style.opacity=blur_opacity/100;	// KLUDGE
		if(start_op == null)
		{
			document.getElementById(id).style.opacity=start_opacity/100;	// KLUDGE
		}
		else
		{
			document.getElementById(id).style.opacity=start_op/100;
		}
	}

	// Call the timer function which actually does the animation
//	OnTimer();
	if(timer == null)
	{
		timer=setTimeout('OnTimer();',opacity_timer);
	}
}

//
//
//
function OnTimer()
{
	// If the timer is set, clear it
	if(timer != null)
	{
		clearTimeout(timer);
		timer=null;
	}

	// See if we are delaying before changing
	if(g_delay > 0)
	{
		g_delay-=opacity_timer;
		timer=setTimeout('OnTimer();',opacity_timer);
		return;
	}

	// See if we need to change the opacity and restart the timer by checking all the current and goal opacities of all the objects in the array.
	var at_goal=true;
	for(i=0;i<ids.length;i++)
	{
		// Get the object's current opacity
		var id=ids[i].id;
		op=document.getElementById(id).style.opacity * 100;
		
		if(op > ids[i].opacity)
		{
			at_goal=false;
			op -= opacity_step;
			op=Math.floor(op);
			document.getElementById(id).style.opacity=op/100;
			document.getElementById(id).style.filter='alpha(opacity='+op+')';
		}
		else if(op < ids[i].opacity)
		{
			at_goal=false;
			op += opacity_step;
			op=Math.floor(op);
			document.getElementById(id).style.opacity=op/100;
			document.getElementById(id).style.filter='alpha(opacity='+op+')';
		}
		else	// else we are at goal and if the goal is 0 and there is a src and the src isn't black.gif set it to blank
		{
			if(op == 0 && id.indexOf("gallery_image_") != -1 && id.indexOf("gallery_image_black_") == -1)
			{
				document.getElementById(id).src='./img/blank.gif';
			}
		}
	}

	// If we are not at goal, restart the timer
	if(at_goal == false)
	{
		timer=setTimeout('OnTimer();',opacity_timer);
	}
}
***/
/*
function ValidateNumericalEdit(id,min,max)
{
	var obj=document.getElementById(id);
	if(obj.value.length == 0)
	{
		return;
	}
	else if(obj.value < min)
	{
		obj.value=min;
	}
	else if(obj.value > max)
	{
		obj.value=max;
	}
}
*/

function SetCookies(user_id,pass_id)
{
	// Get the username and password from the ids
	var user=document.getElementById(user_id).value;
	var pass=document.getElementById(pass_id).value;

	SetCookiesByValue(user,pass);
}

function SetCookiesByValue(user,pass)
{
/***
	setCookie('user',user,365);
	setCookie('pass',pass,365);
***/
	// Set the cookies to expire a year from now
	var d=new Date();								// right now
	d.setTime(d.getTime()+(1000*60*60*24*365));		// add a year (365 days) to right now in ms
	var exp=d.toGMTString();

	document.cookie="user="+user+"; expires="+exp+"; path=/";
	document.cookie="pass="+SHA1(pass)+"; expires="+exp+"; path=/";
}

function ResetCookies()
{
/***	
	setCookie('user','',-365);
	setCookie('pass','',-365);	
***/
	// Set the cookies to expire a year ago
	var d=new Date();								// right now
//	d.setTime(d.getTime()-(1000*60*60*24*365));		// subtract a year (365 days) to right now in ms
	d.setTime(d.getTime()-1000);					// subtract a second from right now in ms
	var exp=d.toGMTString();

	document.cookie="user=; expires="+exp+"; path=/";
	document.cookie="pass=; expires="+exp+"; path=/";
}

// From http://www.w3schools.com/js/js_cookies.asp
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());	
}

// From http://www.w3schools.com/js/js_cookies.asp
function getCookie(c_name)
{
	if(document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
  		if(c_start!=-1)
    	{ 
    		c_start=c_start + c_name.length+1;
    		c_end=document.cookie.indexOf(";",c_start);	
    		if(c_end == -1) 
			{
				c_end=document.cookie.length;
			}
    		
			return unescape(document.cookie.substring(c_start,c_end));
    	} 
  	}

	return "";
}

// Sometimes the browser may auto-fill these inputs if it remembers the values, so we need to remove the background image if there's stuff in the inputs
function checkLoginInputs()
{
	// Check to see if the input edits are visible
	if(document.getElementById("login_username") != null)
	{
		if(document.getElementById("login_username").value.length != 0)
		{
			edit_focus("login_username");
		}
		if(document.getElementById("login_password").value.length != 0)
		{
			edit_focus("login_password");
		}
	}
}

function blog_portfolio_image(portfolio_id)
{
	// Get the current portfolio image
	document.location="edit_blog.php?p="+portfolio_id;
}

function blog_session_image(session_id,image)
{
	// Get the current portfolio image
	document.location="edit_blog.php?s="+session_id+"&i="+image;
}
/*
function ShowSearchDateFormat()
{
	var obj=document.getElementById('query');
	if(obj.value.length == 0)
	{
		obj.value="MM-DD-YYYY";
		obj.select();
	}
}
*/

function CheckSearchDateFormat()
{
	// If date is selected
	var type=document.getElementById('search_type');
	if(type.value == "Date")
	{
		// Check the date format
		var obj=document.getElementById('query');
//		alert(Date.parse(obj.value));
		if(isNaN(Date.parse(obj.value)))
		{
			var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
			var date=new Date();
			alert("Date must be in the format \""+months[date.getMonth()]+" "+date.getDay()+", "+date.getFullYear()+"\"");
//			alert("Date must be in the format \"""\"");
			return false;
		}
	}

	return true;
}

function LimitImageWidthById(id,max_width)
{
	// Get all of the images in this id
	var imgs=document.getElementById(id).getElementsByTagName('img');
	for (j=0;j<imgs.length;j++)
	{
		// Check to see that this image is completely loaded. (Kludge to make it work in Safari)
		if(imgs[j].complete == false || imgs[j].naturalWidth == 0 || imgs[j].width == 0)
		{
			// Try again in a bit
			setTimeout("LimitImageWidthById('"+id+"',"+max_width+");",100);
			return;
		}

		// If the img was loaded, check the width
		if(imgs[j].width > max_width)
		{
			imgs[j].width=max_width;
		}
	}
}

function LimitImageWidthByClass(tag,className,max_width)
{
	// Get all of the tag types with the class className
	var tags=document.getElementsByTagName(tag);
	for(i=0;i<tags.length;i++)
	{
		// If the class matches
		if(tags[i].className == className)
		{
			// Get all of the images in this tag
			var imgs=tags[i].getElementsByTagName('img');
			for (j=0;j<imgs.length;j++)
			{
				// Check to see that this image is completely loaded. (Kludge to make it work in Safari)
				if(imgs[j].complete == false || imgs[j].naturalWidth == 0 || imgs[j].width == 0)
				{
					// Try again in a bit
					setTimeout("LimitImageWidthByClass('"+tag+"','"+className+"',"+max_width+");",100);
					return;
				}

				// If the img was loaded, check the width
				if(imgs[j].width > max_width)
				{
					imgs[j].width=max_width;
				}
			}
		}
	}
}

function click(e)
{
	// IE
	if(document.all)
	{
		// Stops right-click on images in IE.
		if(event.srcElement.tagName=="IMG")
		{
//			if(event.button == 2)
//			{
				alert("Clicking images has been disabled.");	// this needs to be in here to stop the context menu in IE. Safari and FF don't need it.
				return false;
//			}
		}
	}
	else	// FF, Safari
	{
		// Stops right-click on images in FF and Safari.
		if(e.target.tagName=="IMG")
		{
			return false;
		}
	}
}

function printCheck(id)
{
	var obj=document.getElementById('print_option_'+id);
	if(obj.checked)
	{
		document.getElementById('print_option_'+id+'_price_span').style.display='inline';
		document.getElementById('print_option_'+id+'_profit_span').style.display='inline';
	}
	else
	{
		document.getElementById('print_option_'+id+'_price_span').style.display='none';
		document.getElementById('print_option_'+id+'_profit_span').style.display='none';
	}
}

function todo()
{
//	alert("This feature will be available by June 1, the official launch date.");
	alert("This feature is Coming Soon!");
}

function RecalculateProfit(id,base)
{
	// Get the price, and calculate the profit
	var obj=document.getElementById('print_option_'+id+'_price');
	var price=obj.value;
	
	// Calculate the profit from the base price
	var merchant_fee=price * 0.03;	// 3% merchant account fee
	var eppic_fee=price * 0.15;		// 15% eppic surf fee
		
	// Profit is price minus fees and base cost of the print				
	var profit=price-merchant_fee-eppic_fee-base;
	
	if(isNaN(profit))
	{
		profit='Error';
	}
	else if(price != number_format(price,2))
	{
		profit='';
	}
	else
	{
		profit=number_format(profit,2);
	}
	
	// Write the profit
	document.getElementById('print_option_'+id+'_profit').value=profit;
}

function CheckPriceValidity(id)
{
	if(document.getElementById('print_option_'+id+'_profit').value.length == 0)
	{
		alert("Prices must include both dollars and cents.");
		setTimeout("document.getElementById('print_option_"+id+"_price').focus();document.getElementById('print_option_"+id+"_price').select();",0);	
	}
	else if(document.getElementById('print_option_'+id+'_profit').value == 'Error')
	{
		alert("Invalid price.");	
		setTimeout("document.getElementById('print_option_"+id+"_price').focus();document.getElementById('print_option_"+id+"_price').select();",0);	
	}
}

/*** SCRIPT.ACULOU.US code ***/

sortableReordered=false;

function createFavoritesSortable()
{
	Sortable.create('favs',
	{
		tag:'div',
		constraint:'',
		onUpdate:function()
		{
			sortableReordered=true;
		}
	});
	
	// Add ondrag notifier so that once the element is dragged, the click will be ignored. Regardless if onUpdate or onChanged is called.
	// This is to deal with the case where an element is dragged a bit and let go, and it goes back to it's original place.
	Draggables.addObserver(
	{
		onDrag:function()
		{
			sortableReordered=true;
		}
	})
}

function checkSortable(event)
{
	// We are dragging, so this wasn't a normal click	
   	if(sortableReordered) 
	{
        Event.stop(event);
		sortableReordered = false;
   	}
	else
	{
		// This was a click, so now look for the delete link in the html, and get the user from that
		var element=Event.element(event);
		// If they click on a child of the parent (like the image) then get the parent of the element, to get to the div
		if(element.innerHTML == '')
		{
			element=element.parentNode;
		}
/*
		var html=element.innerHTML;
		
//		var user=html.slice(html.indexOf('view_favorites.php?d=')+'view_favorites.php?d='.length,html.indexOf('"',html.indexOf('view_favorites.php?d=')));
		var user=html.slice(html.indexOf('<!--')+'<!--'.length,html.indexOf('-->',html.indexOf('<!--')));
*/
		var user=element.getElementsByTagName('user')[0].innerHTML;
		document.location='view_profile.php?u='+user;
	}
}

// From http://www.fobit.com/index.php?article=JavaScript%3A%20number_format
function number_format (number, decimals, dec_point, thousands_sep)
{
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

function ConfirmPrintDimensions(img_width,img_height)
{
	// Get the width and height for the selected print
	var min_width=0,min_height=0;
	
	// This will keep going until we find the selected print option
	var i=0;
	while(true)
	{
		var obj=document.getElementById('print_option_'+i);
		if(obj && obj.checked)
		{
			min_width=obj.getAttribute('min_width');
			min_height=obj.getAttribute('min_height');
			break;
		}
		i++;
		
		// Sanity check
		if(i > 1000000)
		{
			return false;
		}
	}

	// Now that we have the img dimensions and print dimensions, figure out the longs and shorts of each
	var img_l=img_width;
	var img_s=img_height;
	if(img_width < img_height)
	{
		img_s=img_width;
		img_l=img_height;
	}
	var min_l=min_width;
	var min_s=min_height;
	if(min_width < min_height)
	{
		min_s=min_width;
		min_l=min_height;
	}
	
	// Now see if it is too small in both dimensions
	if(img_l < min_l && img_s < min_s)
	{
		var msg="WARNING : This image is not large enough to support the currently selected print size without potentially noticeable artifacts. It is recommended that you choose either a smaller print size or a different image. Do you still wish to continue?";
		return confirm(msg);
	}
	else if(img_l >= min_l && img_s < min_s)
	{
		// The image is short in the short direction, so suggest CROP and warn about FIT
		var msg="NOTICE : This image is not large enough to FIT the currently selected print size. It is recommended that you choose CROP to avoid potentially noticeable artifacts. Do you still wish to continue?";
		return confirm(msg);
	}

	// The image is larger in both directions, so all is well
	return true;
}

function viewVid(i)
{
	// Change all the video stuff
	document.getElementById('video').innerHTML=vid_embeds[i];	
	document.getElementById('vid_title').innerHTML=vid_titles[i];
	document.getElementById('vid_date').innerHTML=vid_dates[i];
	document.getElementById('vid_desc').innerHTML=vid_descs[i];
	
	if(document.getElementById('vid_user'))
	{
		document.getElementById('vid_user').innerHTML=vid_users[i];
	}
	
	// Get the number of videos
	var count=vid_ids.length;
	
	// Do the next and prev
	if(i == 0)
	{
		document.getElementById('vid_prev').innerHTML="<a href='javascript:viewVid("+(count-1)+");'>< Prev</a>";
	}
	else
	{
		document.getElementById('vid_prev').innerHTML="<a href='javascript:viewVid("+(i-1)+");'>< Prev</a>";
	}
	if(i == count-1)
	{
		document.getElementById('vid_next').innerHTML="<a href='javascript:viewVid(0);'>Next ></a>";
	}
	else
	{
		document.getElementById('vid_next').innerHTML="<a href='javascript:viewVid("+(i+1)+");'>Next ></a>";
	}
	
	// Do the edit
	if(document.getElementById('vid_edit'))
	{
		document.getElementById('vid_edit').innerHTML="<a href='edit_video.php?id="+vid_ids[i]+"'>Edit</a>";
	}
}
















