var top = new Array(); // for flash
var hiResObj = new Object();
var isPhotoPage = false;
var ajaxExtra = '';

function debugLog(text) {
  var ourDate = new Date();
  if (obj = document.getElementById('log'))
    obj.innerHTML += ourDate.toLocaleString() + " " + text + "<br/>";
}

function capitalizeFirstLetters(str) {
  var lower = str.toLowerCase();
  var len = str.length;
  var newWord = true;
  var allLetters = "abcdefghijklmnopqrstuvwxyz";
  for (var i = 0; i < len; i++) {
    var ch = lower.charAt(i);
    if (allLetters.indexOf(ch) == -1)
      newWord = true;
    else if (newWord) {
      newWord = false;
      str = str.substr(i-1, i) + ch.toUpperCase(ch) + str.substr(i+1);
      // str.charAt(i) = ch.toUpperCase(ch);
    }
  }
  return str;
}

function setRadioValue(obj,value) {
	for (var i=0; i<obj.length; i++)
		if (obj[i].value == value)
			obj[i].checked = true;
}

function twoDigit(i)
{
if (i<10) 
  {i="0" + i}
  return i
}

function time() {
	today = new Date();
	h = today.getHours();
	m = today.getMinutes();
	s = today.getSeconds();
	m = twoDigit(m);
	s = twoDigit(s);
	return h + ":" + m + ":" + s;
}

function trim(val) {
	if ( val != null && val.length > 0 ) {
		i = 0;
		while ( val.charAt(i) == ' ' && i < val.length )
			i++;
		if (i > 0)
			val = val.substr(i,val.length-i);
		if ( val.length > 0 ) {
			i = val.length ;
			while ( val.charAt(i-1) == ' ' && i > 0 )
				i--;
			if ( i < val.length )
				val = val.substr(0,i);
		}
	}
	return val;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function fieldEncode(value) {
	var result = "";
	for (var i = 0; i < value.length; i++) {
		hex = (value.charCodeAt(i)  % 256).toString(16);
		result = result + ((hex.length < 2 ? '0' : '') + hex);
	}
	return result + "00"; // ajax seems to get more of this field for some reason, put in a terminator
}


var firstBracesFound = false;

function IEGetElementsByName(name) {
  if (document.getElementsByName)
    return document.getElementsByName(name);
  if (name.length > 2)
    if (name.substr(name.length-3) == "[]") {
      name = name.substr(0, name.length-2);
      if (!firstBracesFound)
        alert("getElementsByName, new name: " + name);
      else
        firstBracesFound = true;
    }
  var objs = new Array();
  var elements = document.getElementsByTagName('*');
  for (var i=0; i < elements.length; i++) {
    if (elements[i].name)
      if (elements[i].name == name)
        objs[objs.length] = elements[i];
  }
  return objs;
}

// Does not work for Explorer
// if (!document.getElementsByName)
//  document.prototype.getElementsByName = function(a) {return IEGetElementsByName(a);}


function setNameVisibility(name, visible) {
  var hideClass = "hidden";
  var objs = getElementsByName(name);
  for (var i=0; i < objs.length; i++) {
    obj = objs[i];
    if (visible) {
      obj.className = trim(obj.className.replace(hideClass, ""));
      obj.className = trim(obj.className.replace(trim(hideClass), ""));
    }
    else
      obj.className = trim(trim(obj.className.replace(hideClass, "")) + " " + hideClass);
  }
}


function setObjClasses(id, classes) {
	currentObj = document.getElementById(id);
	if (currentObj)
		currentObj.className = classes;
}

// can be a sub class, like '-selected', or ' hidden'

function addSubClass(id, subClass) {
	var obj = document.getElementById(id);
	if (obj)
		obj.className = trim(obj.className.replace(subClass, "")) + subClass; // only add once!!
}

function removeSubClass(id, subClass) {
	var obj = document.getElementById(id);
	if (obj) {
		obj.className = trim(obj.className.replace(subClass, ""));
		obj.className = trim(obj.className.replace(trim(subClass), "")); // handle case where adding and removing " b" from either "a" or "".
	}
}

function showObj(id) {
	removeSubClass(id, "hidden");
}

function hideObj(id) {
	addSubClass(id, " hidden");
}

function showHide(showMe, hideMe) {
	showObj(showMe);
	hideObj(hideMe);
}

function isVisibleObj(id) {
  var obj = document.getElementById(id);
  if (obj)
    return obj.className.indexOf("hidden") == -1;
  return false;
}

function deleteObj(id) {
	var obj = document.getElementById(id);
	obj.parentNode.removeChild(obj);
}

function toggleObj(a) {
	obj = document.getElementById(a);
	if (obj) {
		className = obj.className;
		if (className == "hidden")
			obj.className = "";
		else
			obj.className = "hidden";
	}
}

function toggleHelpObj(a) {
	scrollPosition = 0;
	if (typeof window.pageYOffset != 'undefined'){
		scrollPosition = window.pageYOffset;
	}else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0){
		scrollPosition = document.documentElement.scrollTop;
	}
	dialogPosition = scrollPosition + 125;
	obj = document.getElementById(a);
	if (obj) {
		className = obj.className;
		if (obj.style.visibility == "hidden"){
		
			obj.style.visibility = '';
			//obj.className = "";
			document.getElementById("helpInner").style.overflow = "auto";
			obj.style.top = dialogPosition+'px';
		}
		else{
			//obj.className = "invisible";
			obj.style.visibility = 'hidden';
			document.getElementById("helpInner").style.overflow = "hidden";
		}
	}
}

function setObjVisibility(id, visible) {
	if (visible)
		showObj(id);
	else
		hideObj(id);
}

function setInnerHTML(id, html) {
	obj = document.getElementById(id);
	if (obj)
		obj.innerHTML = html;
}

function objValue(id) {
	alert("error, call getObjValue instead...");
}

function getObjValue(id) {
	value = 1;
	var obj = document.getElementById(id);
	if (obj)
		value = obj.value;
	return value;
}

function setObjValue(id, value) {
	var obj = document.getElementById(id);
	if (obj)
		obj.value = value;
}

function copyObjSrc(fromId, toId) {
	fromObj = document.getElementById(fromId);
	toObj   = document.getElementById(toId);
	if (fromObj && toObj)
		toObj.src = fromObj.src;
}

function setObjSrc(id, path) {
	var obj = document.getElementById(id);
	if (obj)
		obj.src = path;
}

function domShift(id, toLeft) {
	obj = document.getElementById(id);
	children = obj.parentNode.childNodes;
	childLength = children.length;
	for (i = 0; i < childLength; i++)
		if (children[i].id == id) {
			x = children[i];
			if (toLeft) {
				if (i == 0) {
					// alert("You go too far sir!");
					return;
				}
				y = children[i-1];
			} else {
				if (i == childLength-1) {
					// alert("You go too far sir!");
					return;
				}
				y = children[i+2];
			}
			obj.parentNode.insertBefore(x,y);
			// alert("swapped i, count, parentId, yId: " + i + ", " + parent.childNodes.length + ", " + parent.id + ", " + y.id);
			return;
		}
	alert("not found.");
}

function isReturn(e) {
	keynum = null;
	if(window.event){ // IE and safari
		keynum = window.event.keyCode;
		}
	else if(e.which){ // Netscape/Firefox/Opera
		keynum = e.which;
		}
	return ((keynum == 13)||(keynum == 3));
}

function handleReturn(id, event, func) {
	handled = false;
	if (isReturn(event)) {
		//handled = true;
		value = getObjValue(id);
		
		if (typeof value == 'string')
			value = '"' + value + '"';
		eval(func + "(" + value + ")");
	}
	return handled;
}

function getHTTPObject() {
	var xmlhttp;

	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		} @else xmlhttp = false;
	@end
	@*/

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}



function closeMenu(id) {
	addSubClass(id, " menu_off");
	setTimeout("removeSubClass('" + id + "', ' menu_off');", 20);
}



// scene strip (SS) thumbnail enlargement - delayed

var ss_timer_id = null;

function ssEnlarge(id) {
	ss_timer_id = setTimeout("addSubClass('ss" + id + "', ' over');", 500);
	// addObjClass("ss" + id, "over", true); // full height
}

function ssReduce(id) {
	if (ss_timer_id)
		clearTimeout(ss_timer_id);
	removeSubClass("ss" + id, " over");
}


// similar to Rada's routine below, but works on a div, which allows live, instant changes without reloading

var timer_id;

function scroll_div(enabled,frm,inc,dir) {
	if (!enabled) // not enough thumbs to scroll
		return;
	if (timer_id)
		clearTimeout(timer_id);
	obj = document.getElementById(frm);
	if (obj) {
		if (dir == "v") {
      		//'top' refers to the window object in Safari, like in frames. Changed var 'top' to 'objTop'. JF 5/2/2007
			objTop = obj.scrollTop;
			objTop = objTop + inc;
			if (objTop < 0)
			objTop = 0;
			obj.scrollTop = objTop;
		}
		else {
			left = obj.scrollLeft;
			left = left + inc;
			if (left < 0)
				left = 0;
			obj.scrollLeft = left;
		}
	// timer_id = setTimeout("scroll_div(true, '" + frm + "'," + inc + ",'" + dir + "')", 20);
	timer_id = setTimeout("scroll_div(true, '" + frm + "'," + inc + ",'" + dir + "')", 20); // 17 ok
	}
}

// Rada Lapsker: 2 functions below make an iframe scroller
// To use, include something like this under iframe:
// <a href="javascript:;" onmouseover="scroll_iframe('selectscene', -4, 'h'); window.status='Scroll left.'; return true" onmouseout="stopScroll(); window.status=''; return true">&laquo;</a>&nbsp;&nbsp;<a href="javascript:;" onmouseover="scroll_iframe('selectscene', 4, 'h'); window.status='Scroll right.'; return true" onmouseout="stopScroll(); window.status=''; return true">&raquo;</a>

function scroll_iframe(frm,inc,dir) {
	if (timer_id)
		clearTimeout(timer_id);
	obj = window.frames[frm];
	if (obj) {
		if (dir == "v")
			obj.scrollBy(0, inc);
		else
			obj.scrollBy(inc, 0);
		timer_id = setTimeout("scroll_iframe('" + frm + "'," + inc + ",'" + dir + "')", 20);
	}
}

function stopScroll() {
	if (timer_id)
		clearTimeout(timer_id);
}


// AJAX routines

var clearAjaxTimer = null;

function clearAjaxStatus() {
	setInnerHTML("ajax_status", "");
}

function setAjaxStatus(status) {
	setInnerHTML("ajax_status", status);
}

function setAjaxRequest(request) {
	setInnerHTML("ajax_request", request);
}

var showAjaxOn = false;

function showAjax() {
	showAjaxOn = !showAjaxOn;
	setObjVisibility("ajax_request", showAjaxOn);
	setObjVisibility("ajax_status", showAjaxOn);
	setObjVisibility("ajax_response", showAjaxOn);
	ajax("action=show_ajax&setting=" + showAjaxOn);
}


function ajaxOld(s) {
	var xmlhttp = getHTTPObject();
	xmlhttp.open("GET", "ajax.php?" + s);
	xmlhttp.send(null);
}

function reloadPage() {
  executeAndReload("a=2");
  // window.location.href = pageUrl; // For non-Safari
  // setTimeout("window.location.href = '/login.php?logout=1';", 1000); // Safari (can't set to same url)
}

function sessionTimeout() {
  // PMJ Feb 11, 2009 - Safari won't allow you to just change window.location here
  alertDialog("Timeout", "For your security, we limit inactive sessions to one hour, please re-login.", 0, "reloadPage", "");
}

function ajax(s) {
	s = s + ajaxExtra;
	// alert("ajaxResult: " + s);
	var xmlhttp = getHTTPObject();
	xmlhttp.open("GET", "/pageclass/ajax.php?" + s);
	var request = time() + " ajax call: <a href='/pageclass/ajax.php?" + s + "'>" + s + "</a>";
	setAjaxRequest(request);
	showObj("ajax_indicator");

	xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
			    hideObj("ajax_indicator");
            if (xmlhttp.status == 200) {
				response = xmlhttp.responseText;
        if (response.indexOf("sessionTimeout()") >= 0) {
          sessionTimeout();
          return;
        }
				setInnerHTML("ajax_response", response.replace("<", "&lt;"));

				eval(response);

				status = time() + " ajax status: " + status;
				setAjaxStatus(status);

				try {
          if (logStr.length > 0)
					  alertDialog("Live Edit", logStr);
        }
        catch (err) {}
				if (!success)
					alert("An error occurred.");
			}
            else if (xmlhttp.status != 0) // June 1, 2010
                alert("error: " + xmlhttp.status);
        }
    }
	xmlhttp.send(null);
}


function executeAndReload(s) {
	s = "/pageclass/ajax.php?" + s + "&reload=" + encodeURIComponent(pageUrl);
	// alert("ajaxAndReload: " + s);
	document.location = s;
}

// PMJ Mar 24, 2009 - called by Ajax

function reduceCount(domId) {
	var obj, value;
	if (obj = $(domId)) {
		value = (1 * obj.innerHTML) - 1;
		obj.innerHTML = value;
	}
}


// helper function for fixDropdownsInIE

function fixNodeHover(node) {
	node.onmouseover=function() {
		this.className+=" over";
	}

	node.onmouseout=function() {
		this.className=this.className.replace(" over", "");
	}
}


// Only CSS is used to implement the dropdown behavior on pages.
// Nested lists are used in conjunction with css :hover pseudo-selectors
// However, IE doesn't support ":hover" on anything other than "a"
// elements. fixDropdownsInIE mimics this ":hover" behavior by
// attaching onmouseover and onmouseout event to list items in IE

function fixDropdownsInIE() {
	if (document.all&&document.getElementById) {  

   // A test to see if the browser is IE5 or higher.
   // Only IE supports document.add and only IE5+
   // supports both document.all and document.getElementById.

		var navRoot = document.getElementById("nav");
		var viewingRoot = document.getElementById("shw");
		var allDivs = document.getElementsByTagName('div');

		if (navRoot != null)
		{
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];

				if (node.nodeName=="LI")
					fixNodeHover(node);
			}
		}

		if (viewingRoot != null)
		{
			for (j=0; j<viewingRoot.childNodes.length; j++) {
				node = viewingRoot.childNodes[j];

				if (node.nodeName=="UL") {
					fixNodeHover(viewingRoot);
				}
			}
		}
		
		// page number dropdown on the paging section
		// buttons showing on top of large image on large.html
		// options section dropdowns on any page that uses "dd" or "hvr" class
		if (allDivs != null) 
		{
			for (var i=0; i < allDivs.length; i++)
			{
				className = allDivs[i].className;
				if (className == "pgn" || className == "image" || className == "dd" || className == "hvr" || className == "dropdown" || className == "dropdownwide") 
					fixNodeHover(allDivs[i]);
			}
		}
		
	}
}

addLoadEvent(fixDropdownsInIE);

var popWinRef;

function LightBoxPopUp(url,winName){
	
	backUrl = document.location.href;
	
	//check for these as they are not standard in any browser
	var x,y;
	if (self.innerHeight){ // all except Explorer
		x = self.outerWidth;
		y = self.outerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight){
		// Explorer 6 Strict Mode
		x = document.documentElement.offsetWidth;
		y = document.documentElement.offsetHeight;
	}
	else if (document.body){ // other Explorers
		x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}

	//popWinRef = window.open(url+'&backUrl='+backUrl,winName,'width='+x+', height='+y+',scrollbars=yes,resizable=yes,status=yes,menubar=yes,toolbar=yes,location=yes');

	popWinRef = window.open(url,'junkvar','width='+x+', height='+y+',scrollbars=yes,resizable=yes,status=yes,menubar=yes,toolbar=yes,location=yes');
}


// email support

function emailPopup(title, url) {
	window.name=title;
	emailWin = window.open(url, 'junkvar','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=570,height=385');
	emailWin.focus();
}


//Generic window open function
function winPop(url,title,options,width,height){
	newWin = window.open(url, 'junkvar',''+options+',width='+width+',height='+height+'');
	newWin.focus();
}

//Begin Hi-res remote download functions.
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

//This is used in Archive and LE.
function remoteSearch(id) {
	ajax("action=remote_search&photo_id="+id, true);
}

//Updates elements on web page if remote files were found.
function remoteUpdatePage(files,displayNames,imgModule,photoId,hiResType,hiResPrice,custom,billingType,extraCharge) {

	var fileJson = files.evalJSON();//Using prototype
	var displayJson = displayNames.evalJSON();

	filesCount = fileJson.length;
	optionHtml = '';//Heading?
	//If there is only one image don't show buttons just use hidden form field.

	if(filesCount>1){
		optionTitle = 'More than one photo is available for download.<br> Please click below to add to your cart:';
	}
	else{
		optionTitle = 'To add this photo to your cart,<br>click on the name of photo below:';
	}
	if (imgModule=='LA')
		optionTitle = 'Download';
	if(imgModule!='LA'){
		optionHtml += '<span><span><table cellpadding="0" cellspacing="0" height="50" id="hiResTable">';
	}
	else{
		// optionHtml += '<span><span><form id="hiResLAForm">';
		optionHtml += '<span><span><table cellpadding="0" cellspacing="0" id="hiResTable" style="width: 90%">';
	}
	
	for(i=0;i<filesCount;i++){
		calulatedPrice = calcPrice(hiResType,hiResPrice,fileJson[i].size);
		calulatedPriceExtra = calulatedPrice+extraCharge;
		calulatedPriceD = '$'+calulatedPriceExtra.toFixed(2);//Price for Display
		if(imgModule=='LE'){
		
			inCartImg  = '';
			rowCss = '';
			
			if(fileJson[i].inCart!=0){
				rowCss = 'cartRow cartRowWhite';
				inCartImg = '<img src="/_images/btn_in_cart.gif"  id="cartButton'+i+'">';
				addText = '<span style="color:red;">Remove</span>';
			}
			else{
				rowCss = 'cartRow';
				inCartImg = '<img src="/_images/btn_cart.gif" id="cartButton'+i+'">';
				addText = '<span style="color:green;">Add Cart</span>';
			}
			
			onClick = 'onclick="hiresToggleCart('+photoId+',\''+fileJson[i].path+'\',\''+hiResType+'\',\''+calulatedPrice+'\',\''+fileJson[i].size+'\','+i+');"';
			
			optionHtml += '<tr id="cartRow'+i+'" class="'+rowCss+'" >';
			
			optionHtml += '<td style="width:20px;padding-right:5px" '+onClick+'> ';
			optionHtml +=  inCartImg;
			optionHtml += '</td>';
			
			optionHtml += '<td style="padding-right:10px" '+onClick+'> ';
			optionHtml += displayJson[i].path;
			optionHtml += '</td>';
			
			optionHtml += '<td style="padding-right:10px" '+onClick+'> ';
			optionHtml += ' ('+ fileJson[i].size+'MB) ';
			optionHtml += '</td>';
			
			optionHtml += '<td style="padding-right:10px" '+onClick+'';
			optionHtml +=  ' '+calulatedPriceD;
			optionHtml += '</td>';

			optionHtml += '<td id="cartText'+i+'" '+onClick+'';
			optionHtml +=  addText;
			optionHtml += '</td>';
			
			if(billingType=='terms'){
			
				optionHtml += '<td style="width:20px; text-align:center; color:white;"> ';
				optionHtml +=  ' | ';
				optionHtml += '</td>';
				
				optionHtml += '<td style="color:white;"  onclick="downloadHiresNowLE('+photoId+',\''+fileJson[i].path+'\',\''+hiResType+'\',\''+calulatedPrice+'\',\''+fileJson[i].size+'\');"> ';
				optionHtml +=  'Download Now';
				optionHtml += '</td>';
			}
			
			optionHtml += '</tr>';
			
		}
		else if(imgModule=='LA'){
			// optionHtml += '<input name="imageName" type="radio" value="'+fileJson[i].path +'" />'+displayJson[i].path+' ('+ fileJson[i].size+'MB)<br/>';
			// PMJ Mar 8, 2010 change layout
			optionHtml += "<tr><td>" + displayJson[i].path + "</td><td>(" + fileJson[i].size + "MB)</td>";
			optionHtml += '<td style="padding-left: 10px; color:white;" class="hover_btn" onclick="downloadHiresNowLE('+photoId+',\''+fileJson[i].path+'\',\''+hiResType+'\',\''+calulatedPrice+'\',\''+fileJson[i].size+'\');"> ';
			optionHtml +=  'Download Now';
			optionHtml += '</td></tr>';
			
		}
	}
	if(imgModule=='LE'){
		optionHtml += '</table></span></span>';
		if(billingType=='terms'){
			dialogOpen(optionTitle, optionHtml, null, null, new Array('checkout', 'continue-look-btn','checkbox_terms'));
		}else{
			dialogOpen(optionTitle, optionHtml, null, null, new Array('checkout', 'continue-look-btn'));
		}
		
	}
	else if(imgModule=='LA'){
		// optionHtml += '</form></span></span>';
		optionHtml += '</table></span></span>';
		hiResObj.photoId = photoId;
		// dialogOpen(optionTitle, optionHtml, null, null, new Array('download-now-btn', 'terms_of_download'));
		// PMJ Mar 8, 2010
		dialogOpen(optionTitle, optionHtml, null, null, new Array('dialog_continue', 'terms_of_download'));
		$('agree_terms').checked = true;
	}

	
}

function checkoutLink(paymentType){
	if($('agree').checked==false){
		alertDialog('Access Denied', 'Please check the box to agree to the download terms.', 10);
		return;
	}
	
	if(paymentType=='cc'){
		document.location.href = '/live_edit/index.php?action=checkout';
	}
	else{
		ajax("action=checkout_terms");
	}
}

function downloadHiresNow(photoId,photoPath,invoiceItemId){
	ajax("action=download_now&photo_id="+photoId+"&photo_path="+photoPath+"&invoice_item_id="+invoiceItemId);
}

function downloadHiresNowLE(photoId,photoPath,hiResType,hiResPrice,fileSize){
	if($('agree_terms').checked==false){
		alert('Please check the box to agree to the download terms.');
		return;
	}
	ajax("action=download_now&photo_id="+photoId+"&photo_path="+photoPath+"&hires_type="+hiResType+"&hires_price="+hiResPrice+"&file_size="+fileSize);
}

function downloadHiresNowLA(){
	//For radios in archive
	if($('hiResLAForm')){
		photoPath = $$('input:checked[name="imageName"]').pluck('value');
		photoId = hiResObj.photoId;
		ajax("action=download_now&photo_id="+photoId+"&photo_path="+photoPath);
	}

}

function hiresToggleCart(photoId,photoPath,hiResType,hiResPrice,fileSize,buttonId){
	ajax("action=toggle_cart&photo_id="+photoId+"&photo_path="+photoPath+"&hires_type="+hiResType+"&hires_price="+hiResPrice+"&file_size="+fileSize+"&button_id="+buttonId);
}

//Used on cart page.
function removeFromCartPage(invoiceItemId,photoFrameId,price){ 
	ajax("action=remove_cart&invoice_item_id="+invoiceItemId);
	if(typeof window.total  != 'undefined'){
		total = (total-price);
		setInnerHTML('totalCost',total.toFixed(2));
		setInnerHTML('totalCostButton',total.toFixed(2));
	}
	$("photoframe" + photoFrameId).remove();
	updateCartCount('remove');
	$("view_cart_tab").update("cart <span style='color: gray;'>("+cartCount+")</span>");
	if(cartCount==0){
		$("checkoutBot").remove();//Remove top cart button
		$("checkoutTop").remove();//Remove bottom cart button
		$("cart1").update('No photos');
	}
}

function removeFromCartDialog(id){
	$('cartButton'+id).src='/_images/btn_cart.gif';
	$('cartRow'+id).removeClassName('cartRowWhite');
	$('cartText'+id).update('<span style="color:green;">Add Cart</span>');
	updateCartCount('remove');
	$('cartButton'+id).blur();
}

function addToCartDialog(id){
	$('cartButton'+id).src='/_images/btn_in_cart.gif';
	$("view_cart_tab").update("cart <span style='color: gray;'>("+cartCount+")</span>");
	$('cartRow'+id).addClassName('cartRowWhite');
	$('cartText'+id).update('<span style="color:red;">Remove</span>');
	updateCartCount('add');
	$('cartButton'+id).blur();
}

function updateCartCount(action){
	if(action=='remove'){
		cartCount = (cartCount-1);
	}
	else if (action=='add'){
		cartCount = (cartCount+1);
	}
	$("view_cart_tab").update("cart <span style='color: gray;'>("+cartCount+")</span>");
	var className = cartCount > 0 ? "hover_btn" : "hidden";
	setObjClasses('checkout_btn', className);
}

function calcPrice(hiResType,hiResPrice,size){
	hiResPrice = parseFloat(hiResPrice);
	if(hiResType==2){
		//Charge per MB
		price = (hiResPrice*size);
	}
	else{
		//Charge per image
		price = hiResPrice;	
	}
	return price;
}

function hiResTermsCheck(inputObj){
	if(inputObj.checked==true){
		ajax("action=hires_terms&val=1");
	}
	else{
		ajax("action=hires_terms&val=0");
	}
}

function hiresCheckout(){
	ajax("action=checkout_save&"+$('checkout').serialize());
}

function editExtraCharges(photoId){
	ajax("action=get_extra_charges&photo_id="+photoId);
}

function addExtraCharge(){
	item  = $('extra_item').value;
	amount = $('extra_amount').value;
	if(!item || !amount){
		alert('Please fill out both fields.');
		return false;
	}
	ajax("action=add_extra_charges&photo_id="+hiResPhotoId+"&amount="+amount+"&item="+item );
}
function deleteExtraCharge(photoId,extraChargeId){
	ajax("action=delete_extra_charges&extra_charge_id="+extraChargeId+"&photo_id="+photoId);
}
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//End Hi-res remote download functions.


function infoPanelSession(status){
	ajax("action=set_session_production&val="+status);
}

//validate agreement check for agreement_accept.php
function agreementCheck(){
	if(document.getElementById('agree').checked==false){
		showObj('warning');
		return false;
	}
	else{
		return true;
	}
}


//Clients page edit and retoucher.
function expandShoots(clientId){
	//Toggle submenu
	Effect.toggle( 'client'+clientId, 'blind', {duration: 0 } );
	//swap class to change image
	$('arrow'+clientId).toggleClassName('arrowDown');
	return false;
}


//Remove a folder of uploaded images before they are imported.
function uploadDelete(shotName, folderBlock, module) {
	if (confirm("Are you sure you want to delete the folder '" + shotName + "'?")){
		ajax("action=upload_dir_delete&shot_name=" + shotName + "&module="+module+"&element_id="+folderBlock);
	}

}

//Sound functions for login/marketing
//These are a hack to get sound integrated with slimbox.
//Safari 2 won't let you stop a sound if it's played through swapping src or toggling display so use iframes.
//

function playHidden(audioPath){
	document.getElementById('hiddenSound').src = '/_includes/login/sound.php?audio_path='+audioPath;
}

function stopHidden(){
	document.getElementById('hiddenSound').src = '/_includes/login/sound.php';
}

// Loupe Code

var currLoupePhotoId = null;

function loupe(photoId) {
	currLoupePhotoId = photoId;
  ajax('action=loupe&photo_id=' + photoId);
}

var LoupeSettings = new Object();

// called by Ajax

function setLoupeParams(name, picsmall, picbig, ws, hs, wl, hl, brdr) {
  LoupeSettings.picsmall = picsmall;
  LoupeSettings.picbig   = picbig;
  LoupeSettings.ws       = ws;
  LoupeSettings.hs       = hs;
  LoupeSettings.wl       = wl;
  LoupeSettings.hl       = hl;
  LoupeSettings.brdr     = brdr;
  pageTop();
  setInnerHTML('loupe_file_name', name);
  // showObj('log');
  var size = getPageSize();
  $('loupe_lightbox').style.height = size[1] + "px";
  showObj('loupe_lightbox');
  showObj('loupe_overlay');
  if (loupeSucceeded) // PMJ Feb 20, 2009 - Explorer didn't work
    initializeLoupe();
}

function thisMovie(movieName) {
  var isIE = navigator.appName.indexOf('Microsoft') != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

var loupeFails = 0;
var loupeSucceeded = false;

function initializeLoupePhase2() {
  if (thisMovie('magnifier3_3_2').controlMovie)
    ;
  else {
    setTimeout("initializeLoupe();", 300);
    return;
  }
  try {
    with (LoupeSettings) {
      thisMovie('magnifier3_3_2').controlMovie(hh, magsize, picsmall, picbig, ws, hs, wl, hl, brdr);
    }
  }
  catch (e) {
    // alert("Error name: " + e.name + ". Error description: " + e.description + ". Error number: " + e.number + ". Error message: " + e.message);
    loupeFails++;
    hideObj('loupe_lightbox');
    hideObj('loupe_overlay');
    if (loupeFails < 3)
      // setTimeout("initializeLoupePhase2();", 200);
      setTimeout("showObj('loupe_lightbox');showObj('loupe_overlay');", 1000); // try and get it going again
  }
}

function initializeLoupe_UNUSED() {
  var magsize = 1.5;
  var hh = 1;
  var i = 1;
  var obj;
  with (LoupeSettings) {
    // size the flash for this image
    obj = document.getElementById("magnifier3_3_2");
    i = 2;
    widthLoupe  = ws + brdr * 4;
    heightLoupe = hs + brdr * 4;
    i = 3;
    obj.width = widthLoupe;
    obj.height = heightLoupe;
    i = 4;
    try {
      document.magnifier3_3_2.width = widthLoupe;
      i = 5;
      document.magnifier3_3_2.height = heightLoupe;
    }
    catch (e) {}
    i = 6;
    vertAlign('loupe_table');
  }
  setTimeout("initializeLoupePhase2();", 300);
}


function initializeLoupe() {
  var magsize = 1.5;
  var hh = 1;
  var i = 1;
  try {
    with (LoupeSettings) {
      // size the flash for this image
      var obj = document.getElementById("magnifier3_3_2");
      i = 2;
      widthLoupe  = ws + brdr * 4;
      heightLoupe = hs + brdr * 4;
      i = 3;
      obj.width = widthLoupe;
      obj.height = heightLoupe;
      i = 4;
      try {
        document.magnifier3_3_2.width = widthLoupe;
        i = 5;
        document.magnifier3_3_2.height = heightLoupe;
      }
      catch (e) {}
      i = 6;
      vertAlign('loupe_table');
      // load it up
      i = 7;
      thisMovie('magnifier3_3_2').controlMovie(hh, magsize, picsmall, picbig, ws, hs, wl, hl, brdr);
      i = 8;
      loupeSucceeded = true;
    }
  }
  catch (e) {
    loupeFails++;
    // hideObj('loupe_lightbox');
    // hideObj('loupe_overlay');
    if (loupeFails < 6)
      // setTimeout("showObj('loupe_lightbox');showObj('loupe_overlay');", 300); // try and get it going again
      setTimeout("loupeAgain();", 250); // try and get it going again
  }
}

function loupeAgain() {
  // hideObj('loupe_lightbox');
  hideObj('loupe_overlay');
  // setTimeout("showObj('loupe_lightbox');showObj('loupe_overlay');", 50);
  setTimeout("showObj('loupe_overlay');", 50);
}

function flashready(str){
  setTimeout('initializeLoupe();', 100); // 100
  return 'ready';
}

function imagesloaded(str){
  return 'ok';
}

function pageTop() {
  document.body.scrollTop = 0;
}

function getWindowHeight() {
  if (self.innerHeight) {
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) {
    windowHeight = document.body.clientHeight;
  }
  return windowHeight;
}

function vertAlign(containerName) {
  var winHeight = getWindowHeight();
  var obj = document.getElementById(containerName);
  if (obj) {
    if (winHeight > 0) {
      if (winHeight - obj.offsetHeight > 0) {
        obj.style.position = "relative";
        var newTop = winHeight / 2 - obj.offsetHeight / 2 + "px";
        obj.style.top = newTop;
      }
      else {
        obj.style.position = "static";
      }
    }
  }
}

window.onresize = function() {
  vertAlign("loupe_table");
}

// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
  
  var xScroll, yScroll;
  
  if (window.innerHeight && window.scrollMaxY) {  
    xScroll = document.body.scrollWidth;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  
  var windowWidth, windowHeight;
  if (self.innerHeight) {  // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }  
  
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else { 
    pageHeight = yScroll;
  }

  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){  
    pageWidth = windowWidth;
  } else {
    pageWidth = xScroll;
  }


  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
  return arrayPageSize;
}

function showUpdatePaymentDialog(){
	document.location.href = "/public/cc_update.php";
}

function getScrollingPosition() {
  var position = [0, 0];
  if (typeof window.pageYOffset != 'undefined')
    position = [window.pageXOffset,window.pageYOffset];
  else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0)
    position = [document.documentElement.scrollLeft,document.documentElement.scrollTop];
  else if (typeof document.body.scrollTop != 'undefined')
    position = [document.body.scrollLeft,document.body.scrollTop];
  return position;
}

function imageHover(id, imageUrl,width){
	new Tip(id, imageUrl, {
	viewport:true,
	delay:0,
	width: width, 
	border: 0, 
	radius: 0,
	offset: { x: 1, y: 1 }
	});
}

// PMJ Dec 11, 2008 - new image hover, not constrainted to current mouse location, centered to work with larger images

var hoverItems = new Array();
var hoverOpen = false;
var hoverTimer = null;
var hoverId = null;
var hoverStartTime = null;
var hoverImageDomId = null;
// var imageHoverSize = 1; // 1 = original, 2 = medium

function setImageHoverSize(sizeKind) {
  imageHoverSize = sizeKind; // PMJ Mar 13, 2009
  var obj;
  if (obj = $('hoverimage_menu'))
    if (imageHoverSize == 1)
      obj.className = "ilarge";
    else
      obj.className = "imedium";
  ajax("action=set_image_hover_size&size=" + imageHoverSize);
}

function toggleHover() {
  if (imageHoverSize == 1)
    imageHoverSize = 2;
  else
    imageHoverSize = 1;
  setImageHoverSize(imageHoverSize);
}

var prevHoverImagePhotoId = null;

function imageHover2(photoId, label, id, width, height, fullWidth, fullHeight){
  var title      = $(id).innerHTML;
  var obj        = new Object();
  obj.photoId    = photoId;
  obj.title      = title;
  obj.label      = label;
  obj.width      = new Array();
  obj.height     = new Array();
  obj.width[1]   = fullWidth;
  obj.height[1]  = fullHeight;
  obj.width[2]   = width;
  obj.height[2]  = height;
  hoverItems[id] = obj;
  var domObj     = $(id);
  // domObj.onmouseover = function() { var wait = id==prevHoverImagePhotoId ? 600 : 200; hoverTimer = setTimeout("imageHoverShow('" + id + "');", wait); };
  domObj.onmouseover = function() { hoverTimer = setTimeout("imageHoverShow('" + id + "');", 200); };
  // domObj.onmouseover = function() { var wait = id==prevHoverImagePhotoId ? 1 : 200; hoverTimer = setTimeout("imageHoverShow('" + id + "');", wait); };
  domObj.onmouseout  = function() { imageHoverHide(); }
}

function imageHoverShow(id) {
  prevHoverImagePhotoId = id;
  var currentTime = new Date()
  hoverStartTime = currentTime.getTime(); // milliseconds
  var item = hoverItems[id];
  var imageWidth = item.width[imageHoverSize];
  var size = getPageSize();
  var obj = $('hoverimage_table'); // hoverimage
  // ************* TODO ************** Explorer and probably Safari reload the image each time from the server
  // ************* therefore must make img tags that stick around
  var scrollTop = getScrollingPosition()[1];
  var tempImageHoverSize = imageHoverSize; // PMJ Apr 17, 2009
  if (isPhotoPage)
  	tempImageHoverSize = 1; // always large	
  var topOffset = tempImageHoverSize == 1 ? 10 : 110; 
  obj.style.top = (topOffset + scrollTop) + "px";
  obj.style.left = ((size[2] - imageWidth) / 2) + "px";
  obj = $('hoverimage_table');
  obj.onmouseout = function() {imageHoverHide();};
  obj.onmousemove = function(e) { imageHoverMouseMove(e); };
  setInnerHTML('hoverimage_title', item.label);
  obj.className = ''; // show
  obj = $('hoverimage_content');
  var temp = hoverItems[id];
  var domImageId = "hoverimage" + temp.photoId + "_" + tempImageHoverSize;
  var url = "/getimage.php?photo_id=" + temp.photoId + "&size=" + tempImageHoverSize;
  if (false) {
    obj.innerHTML = "<img id='" + domImageId + "' src='" + url + "' width='" + temp.width[tempImageHoverSize] + "' height='" + temp.height[tempImageHoverSize] + "'/>"; // hoverItems[id].url;
  }
  else {
    if ($(domImageId))
      showObj(domImageId);
    else {
      var newImg    = document.createElement('img');
      newImg.id     = domImageId
      newImg.src    = url;
      newImg.alt    = '';
      newImg.width  = temp.width[tempImageHoverSize];
      newImg.height = temp.height[tempImageHoverSize];
      obj.appendChild(newImg);
    }
  }
  hoverImageDomId = domImageId;
  hoverOpen = true;
}

function imageHoverShow_UNUSED(id) {
  prevHoverImagePhotoId = id;
  var currentTime = new Date()
  hoverStartTime = currentTime.getTime(); // milliseconds
  var item = hoverItems[id];
  var imageWidth = item.width[imageHoverSize];
  var size = getPageSize();
  var obj = $('hoverimage_table'); // hoverimage
  // ************* TODO ************** Explorer and probably Safari reload the image each time from the server
  // ************* therefore must make img tags that stick around
  var scrollTop = getScrollingPosition()[1];
  var topOffset = imageHoverSize == 1 ? 10 : 110; 
  obj.style.top = (topOffset + scrollTop) + "px";
  obj.style.left = ((size[2] - imageWidth) / 2) + "px";
  obj = $('hoverimage_table');
  obj.onmouseout = function() {imageHoverHide();};
  obj.onmousemove = function(e) { imageHoverMouseMove(e); };
  setInnerHTML('hoverimage_title', item.label);
  obj.className = ''; // show
  obj = $('hoverimage_content');
  var temp = hoverItems[id];
  var domImageId = "hoverimage" + temp.photoId + "_" + imageHoverSize;
  var url = "/getimage.php?photo_id=" + temp.photoId + "&size=" + imageHoverSize;
  if (false) {
    obj.innerHTML = "<img id='" + domImageId + "' src='" + url + "' width='" + temp.width[imageHoverSize] + "' height='" + temp.height[imageHoverSize] + "'/>"; // hoverItems[id].url;
  }
  else {
    if ($(domImageId))
      showObj(domImageId);
    else {
      var newImg    = document.createElement('img');
      newImg.id     = domImageId
      newImg.src    = url;
      newImg.alt    = '';
      newImg.width  = temp.width[imageHoverSize];
      newImg.height = temp.height[imageHoverSize];
      obj.appendChild(newImg);
    }
  }
  hoverImageDomId = domImageId;
  hoverOpen = true;
}

function imageHoverHide() {
  if (hoverTimer)
    clearTimeout(hoverTimer);
  hoverTimer = null;
  var currentTime = new Date()
  if (currentTime.getTime() - hoverStartTime < 100)
    return; // image was brought up on top of the filename
  imageHoverCoords = null;
  hideObj('hoverimage_table'); // hoverimage
  hideObj(hoverImageDomId);
}


var imageHoverCoords = null;

function imageHoverMouseMove(e) {
  var isIE = window.event ? true : false;
  if (isIE) {
    tempX = event.clientX;
    tempY = event.clientY;
  } else {
    tempX = e.pageX;
    tempY = e.pageY;
  }
  if (imageHoverCoords) {
    if (Math.abs(tempX - imageHoverCoords.x) > 40 || Math.abs(tempY - imageHoverCoords.y) > 10)
      imageHoverHide();
  }
  else {
    imageHoverCoords = new Object();
    imageHoverCoords.x = tempX;
    imageHoverCoords.y = tempY;
  }
}

function deleteInfoDocAction(shootId, name, isPrivate) {
  isPrivate = isPrivate ? "true" : "false";
  ajax('action=delete_shoot_info&shoot_id=' + shootId + '&name=' + name + '&private=' + isPrivate);
}

function deleteInfoDoc(shootId, name, isPrivate) {
  isPrivate = isPrivate ? "true" : "false";
  confirmDeleteDialog("Shoot Info", "Delete info file <b>" + name + "</b>", 'deleteInfoDocAction', shootId + ',"'+name+'",' + isPrivate);
}

function paySubmit(){
	ajax("action=pay_submit&"+$('payment').serialize());
}
//Wrapper for dialogs.
function back(){
	parent.history.back()
}

function hiresDownloadCBox(photoId) {
	var obj;
	if (obj = $("cbox_" + photoId)) {
		var state;
		if (obj.checked)
			state = "on";
		else
			state = "off";
		ajax("action=hires_download_cbox&photo_id=" + photoId + "&state=" + state);
	}
}

function showEXIFDialog(photoId) {
	ajax("action=show_exif_dialog&photo_id=" + photoId);
}

var onLoadCode = '';

function executeOnLoadCode() {
	eval(onLoadCode);
}

function setOnLoadCode(js) {
	onLoadCode = js;
}

function toggleHelpVideos() {
	if($('no_help_intro_cbox').checked==false){
		val = 0;
	}
	else{
		val = 1;
	}
	ajax('action=no_help_intro&value='+val);
}

function getStartedVidHelp(){
	html = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="656" height="385" codebase="http://www.apple.com/qtactivex/qtplugin.cab"> <param name="src" value="/video/gettingstarted.mp4"> <param name="autoplay" value="true"> <param name="controller" value="true"> <param name="loop" value="true"> <embed src="/video/gettingstarted.mp4" width="656" height="385" autoplay="true" controller="true" loop="true" pluginspage="http://www.apple.com/quicktime/download/"> </embed></object><br/><br/><label style="font-weight:bold;"><span><span><input type="checkbox" id="no_help_intro_cbox" name="no_help_intro_cbox" value="1" onclick="toggleHelpVideos();"/></span></span> Do not show again.</label>';
	getStartedVidDialog(html)
}

function getStartedVidDialog_UNUSED(html){
	alertDialog('Getting Started',html);
	setDialogWidth(712);
	size = getPageSize();
	scrollTop = getScrollingPosition()[1];
	getStartedTop = Math.round(scrollTop + (size[3] - 508) / 2);
	if(getStartedTop<5){
		getStartedTop = 5;
	}
	setDialogTop(getStartedTop);
	$('dialog_title').style.fontWeight = 'bold';
	$('dialog_message').style.textAlign = 'left';
}

function getStartedVidDialog(html){
	html = '';
	alertDialog('Getting Started',html);
	setDialogWidth(712);
	size = getPageSize();
	scrollTop = getScrollingPosition()[1];
	getStartedTop = Math.round(scrollTop + (size[3] - 508) / 2);
	if(getStartedTop<5){
		getStartedTop = 5;
	}
	setDialogTop(getStartedTop);
	hideObj('dialog_message');
	showObj('welcome_video_container'); // PMJ Oct 16, 2009
	$('dialog_title').style.fontWeight = 'bold';
	$('dialog_message').style.textAlign = 'left';
}

function waitFor(millis) 
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); } 
while(curDate-date < millis);
}