var g_popupMainElem;
var savedPopupElem, g_savedAnimElem;

var prBox;
var g_colorPickerOpen = false; // hack


//-------------------------------------------------------
function killPrBox () {
if (prBox) {
	document.body.removeChild (prBox);
	prBox = null;
	}
}

var popuppic_showDebug = false;

//-------------------------------------------------------
function pr (string, time) {
if (prBox) {
	if (prBox.timerHandle)
		EventHandlers.cancelTimerFunction (prBox.timerHandle);
	document.body.removeChild (prBox);
	}
var winDims = GeneralUtils.getWindowDimensions ();
var el = GeneralUtils.createElementOld;
prBox = el ("div", {style: {position: "absolute", zIndex: "500", left: (winDims.scrollX + 50)+"px", top: (winDims.scrollY + 50)+"px", padding: "5px", border: "1px solid black", backgroundColor: "#ffd"}, innerHTML: string});
document.body.appendChild (prBox);
prBox.timerHandle = EventHandlers.setTimerFunction (killPrBox, ((time)?time:3000));
}
/*
//---------------------------------------
// todo: belongs in general utils 
function checkElementForAncestry (el) {
for (var i = 1; i < arguments.length; i++) {
	var t = el;
	if (arguments[i]) {
		while (t) {
			if (t == arguments[i])
				return true;
			t = t.parentNode;
			}
		} 
	}
return false;
}
*/

function checkElementForNoHideTag (el) {
if (g_colorPickerOpen)
	return true;
var t = el;
while (t) {
	if (t.noHide || t.karmaticsPopup) {
		return true;
		}
	t = t.parentNode;
	}
return false;
}


//-------------------------------------------------------
function popuppic_makeAnimElement (styleInfo, filled) {
var d = document.createElement ('DIV');
d.style.position = 'absolute';

d.style.zIndex = Popup.getZ();
d.className = styleInfo.startPhrase + "animrect";
d.style.borderColor = styleInfo.borderColor;
if (filled)
	d.style.backgroundColor =  styleInfo.borderColor;
d.style.borderStyle = 'solid';
d.style.borderWidth = '10px';
d.style.display = 'none';
document.body.appendChild (d);
return d;
}

//-------------------------------------------------------
function popuppic_removeImageAndCaptionElems (elem, delay) {
if (!elem) return;

if (delay)
	EventHandlers.setTimerFunction ([popuppic_removeImageAndCaptionElems, elem], delay);
else
	{
	document.body.removeChild (elem);
	document.body.removeChild (elem.captionTable);
	}
}

//-------------------------------------------------------
function popuppic_removeAnimElem (elem, delay) {
if (!elem) return;

if (delay)
	EventHandlers.setTimerFunction ([popuppic_removeAnimElem, elem], delay);
else
	document.body.removeChild (elem);
}

//-------------------------------------------------------
function popuppic_keystrokeCommand (evt) {
if (!evt)
	evt = aardvark.window.event;
var keyCode = evt.keyCode ? evt.keyCode :
			evt.charCode ? evt.charCode :
			evt.which ? evt.which : 0;
var c = String.fromCharCode(keyCode).toLowerCase();
switch (c) {
	case 'h':
		popuppic_hidePopup ();
		killPrBox ();
		break;
	case 'd': 
		popuppic_showDebug = !popuppic_showDebug;
		break;
	case 'c': 
		document.title = "- ";
		break;
	case 'y':
		popuppic_loadImage (sfsc_data.showroomImageData.blockList[1], 2);
		break;
		
	}
}

//-------------------------------------------------------
function popuppic_setClickHandler () {
EventHandlers.setListener (document, "click", popuppic_bgClick, false);
EventHandlers.setListener (document, "keydown", popuppic_keystrokeCommand);
}
//-------------------------------------------------------
function popuppic_bgClick (evt) {
var elem = ((evt.target) ? evt.target : evt.srcElement);
if (g_popupMainElem) {
	if (checkElementForNoHideTag (elem) == false) {
		popuppic_hidePopup ();
		}
	}
}

//------------------------------------------------
// often called from timer func
function popuppic_displayImageAndCaption (ai) {
ai.isComplete = true;
if (ai.isLoaded) {
		ai.img.style.backgroundColor = ai.imageData[2];
		ai.img.style.visibility = "visible";
		}
g_popupMainElem.style.visibility = 'visible';
g_popupMainElem.captionTable.style.visibility = "visible";
}

//------------------------------------------------
// often called from timer func
function popuppic_popupAnim (ratio, animInfo) {
if (ratio > 1.0){
	if (animInfo.expand)
		popuppic_displayImageAndCaption (animInfo);
	popuppic_removeAnimElem(animInfo.elem, 20);
	return;
	}
var d = animInfo.elem;
var b = Math.round (ratio*6);
d.style.borderWidth = ((animInfo.expand)?(3+b):(9-b)) + 'px';
GeneralUtils.moveElem (d, (animInfo.x2 - animInfo.x1) * ratio + animInfo.x1, (animInfo.y2 - animInfo.y1) * ratio + animInfo.y1);
d.style.width = ((animInfo.w2 - animInfo.w1) * ratio + animInfo.w1) + 'px';
d.style.height = ((animInfo.h2 - animInfo.h1) * ratio +	animInfo.h1) + 'px';
d.style.display = '';
EventHandlers.setTimerFunction ([popuppic_popupAnim, [(ratio + animInfo.ratioAdder), animInfo]], 20);
}

//-------------------------------------------------------
function popuppic_hidePopup () {
var d = g_popupMainElem;
if (d && d.style.visibility != "hidden") {
	var ai = {};
	ai.elem = popuppic_makeAnimElement(g_popupMainElem.block.styleInfo);
	
	var bigImage = d.popupImage;
	var smallElem = d.block.list[d.index].thumbnailElem;
	
	if (bigImage && smallElem) {
		var bigPos = GeneralUtils.getPos (bigImage);
		var smallPos = GeneralUtils.getPos (smallElem);
		ai.x1 = bigPos.x;
		ai.x2 = smallPos.x;
		ai.y1 = bigPos.y;
		ai.y2 = smallPos.y;
		ai.w1 = bigImage.offsetWidth;
		ai.h1 = bigImage.offsetHeight;
		ai.w2 = smallElem.offsetWidth;
		ai.h2 = smallElem.offsetHeight;
		ai.expand = false;
		
		var diff = Math.abs(ai.y2-ai.y1) + Math.abs(ai.x2-ai.x1) + Math.abs(ai.w2-ai.w1) + Math.abs(ai.h2-ai.h1);
		ai.ratioAdder = (diff<100)?1:(diff<200)?.2:(diff<400)?.13:(diff<600)?.09:.065;
		
		// overkill?
		g_popupMainElem.block = null;
		document.body.removeChild (g_popupMainElem.captionTable);
		g_popupMainElem.captionTable = null;
		document.body.removeChild (g_popupMainElem);
		g_popupMainElem = null;
		popuppic_popupAnim (.1, ai);
		}
	}
}

function popuppic_imageLoadCallback (imgData, ai) {
// this should only be for colorizer
if (ai.isComplete) {
		ai.img.style.visibility = "visible";
		ai.img.style.backgroundColor = ai.imageData[2];
		}
ai.isLoaded = true;
}

//-------------------------------------------------------
function popuppic_loadImage (block, index, useLastPopup)
{
var el = GeneralUtils.createElementOld;
if (!block.styleInfo)
	block.styleInfo = {startPhrase: "", borderColor: "#666"};
var styleInfo = block.styleInfo;
var imgData = block.list[index];
var savedPopupElem = null;
var windowDims = GeneralUtils.getWindowDimensions ();

var startDims, alignY;

if (useLastPopup) {
	startDims = GeneralUtils.getPos(g_popupMainElem);
	startDims.width = g_popupMainElem.offsetWidth;
	startDims.height = g_popupMainElem.offsetHeight;
	var p = GeneralUtils.getPos(g_popupMainElem.captionTable);
	alignY = p.y;
	}
else {
	startDims = GeneralUtils.getPos(imgData.thumbnailElem);
	startDims.width = imgData.thumbnailElem.offsetWidth;
	startDims.height = imgData.thumbnailElem.offsetHeight;
	}

if (g_popupMainElem) {
	g_popupMainElem.animInfo = null;
	g_popupMainElem.block = null;
	savedPopupElem = g_popupMainElem;
	}

var c, captionTable;
var z = Popup.getZ();
c = el ("div", {className: styleInfo.startPhrase + "photocontainer", style:{position: "absolute", zIndex: z, left:  windowDims.scrollX + "px", top: windowDims.scrollY + "px", visibility: "hidden"}});
document.body.appendChild (c);
g_popupMainElem = c;
c.block = block;
c.index = index;

captionTable = el("table", {className: styleInfo.startPhrase + "photocaption", style: {position: "absolute", zIndex: z, left: windowDims.scrollX + "px", top: windowDims.scrollY + "px", visibility: "hidden"}});
g_popupMainElem.captionTable = captionTable;
document.body.appendChild (captionTable);

var bigWidth = imgData.wL, bigHeight = imgData.hL;

var mainImage = el ("img", {style:{width: imgData.wL + "px", height: imgData.hL + "px", cursor: "pointer"}});
g_popupMainElem.popupImage = mainImage; // needed?
c.appendChild (mainImage);


var tr1, tr2, tbody;

tbody = el("tbody", null, tr1 = el("tr"), tr2 = el("tr"));

if (index > 0) {
	img1 = el("img", {src: block.path + block.list[index-1][0]+ "-small." + block.ext, style:{width: block.list[index-1].wS + "px", height: block.list[index-1].hS + "px"}});
	tr1.appendChild (el("td", {className: styleInfo.startPhrase + "thumbnail", noHide: true},	img1));
	tr2.appendChild (el("td", {className: styleInfo.startPhrase + "prevNext", noHide: true},
		a = el ("a", {href: "#"}, "previous")		
		));
	EventHandlers.setEventHandler (img1, "onclick",  [popuppic_loadImage, [block, index-1, true]]);
	EventHandlers.setEventHandler (a, "onclick",  [popuppic_loadImage, [block, index-1, true]]);
	}
else {
	tr1.appendChild (el("td", {style: {width: "50px"}}));
	tr2.appendChild (el("td", {style: {width: "50px"}}));
	}

var innerElems = {};
tr1.appendChild (
	GeneralUtils.createDomElems(["td", {className: styleInfo.startPhrase + "captionText", rowSpan: "2"},
		innerElems.colorThing = ["div", {style: {color: "#aaa",		
		cssFloat: "left", styleFloat: "left", cursor: "pointer", padding: "2px", margin: "2px 20px 8px 2px", border: "1px solid #aaa", backgroundColor: imgData[2]}}, "change", ["br"], imgData[3], ["br"], "color"],
		{ html: imgData[1] }
		], innerElems)
	);
	
Chameleon.initElements (mainImage, null, innerElems.colorThing, popuppic_chameleonCallback);
innerElems.colorThing.noHide = true;
mainImage.imgData = imgData; // hack


if (index < block.list.length-1) {
	img2 = el("img", {src: block.path + block.list[index+1][0]+ "-small." + block.ext,  style:{width: block.list[index+1].wS + "px", height: block.list[index+1].hS + "px"}});
	tr1.appendChild (el("td", {className: styleInfo.startPhrase + "thumbnail", noHide: true},	img2));
	tr2.appendChild (el("td", {className: styleInfo.startPhrase + "prevNext", noHide: true},
		a = el ("a", {href: "#"}, "next")));
	EventHandlers.setEventHandler (img2, "onclick",  [popuppic_loadImage, [block, index+1, true]]);
	EventHandlers.setEventHandler (a, "onclick", [popuppic_loadImage, [block, index+1, true]]);
	}	
else {
// todo
	tr1.appendChild (el("td", {style: {width: "50px"}}));
	tr2.appendChild (el("td", {style: {width: "50px"}}));
	}
captionTable.appendChild (tbody);
var totalHeight = bigHeight + captionTable.offsetHeight;	

var ai = {};
ai.x1 = startDims.x;

ai.x2 = ai.x1 + startDims.width/2 - (bigWidth/2 + 10);
ai.y1 = startDims.y;
if (useLastPopup)
	ai.y2 = alignY  - (bigHeight + 10);
else
	ai.y2  = ai.y1 + startDims.height/2 - (totalHeight/2 + 10);
ai.w1 = startDims.width;
ai.h1 = startDims.height;
ai.w2 = bigWidth;
ai.h2 = bigHeight;
ai.expand = true;
ai.imageData = imgData;
ai.img = mainImage;
var wh = windowDims.scrollX + windowDims.width - 6;

if (ai.x2 < 3)
	ai.x2 = 3;
else if (ai.x2 > windowDims.width - (bigWidth + 40))
	ai.x2 = windowDims.width - (bigWidth + 40);

var ctX = ai.x2 + bigWidth/2 - captionTable.offsetWidth/2 + 10;
if (totalHeight > windowDims.height)
	{
	ai.y2 = windowDims.scrollY - 10 +  windowDims.height/2 - bigHeight/2;
	GeneralUtils.moveElem (captionTable, ctX, windowDims.scrollY + windowDims.height - captionTable.offsetHeight);
	}
else
	{
	if (ai.y2 < windowDims.scrollY)
		ai.y2 = windowDims.scrollY; 
	else if (ai.y2  + totalHeight + 24 > windowDims.scrollY + windowDims.height)
	 ai.y2 = windowDims.scrollY + windowDims.height - (totalHeight+10);
	GeneralUtils.moveElem (captionTable, ctX, ai.y2 + bigHeight + 10);
	}
if (useLastPopup)
		captionTable.style.visibility = "visible";
var diff = Math.abs(ai.y2-ai.y1) + Math.abs(ai.x2-ai.x1) + Math.abs(ai.w2-ai.w1) + Math.abs(ai.h2-ai.h1);
ai.ratioAdder = (diff<100)?.95:(diff<200)?.2:(diff<400)?.13:(diff<600)?.09:.065;
GeneralUtils.moveElem (c, ai.x2, ai.y2);

if (popuppic_showDebug) {
	var s = "";
	for (var x in ai) {
		var s2 = "";
		for (var y in ai[x])
			s2 += "{" + y + ": " + ai[x][y] + "} ";
		if (s2.length > 0)
			s += x + ": " + s2 + "<br>";
		else 
			s += x + ": " + ai[x] + s2 + "<br>";
		}
	for (var x in windowDims) {
		var s2 = "";
		for (var y in windowDims[x])
			s2 += "{" + y + ": " + windowDims[x][y] + "} ";
		if (s2.length > 0)
			s += x + ": " + s2 + "<br>";
		else 
			s += x + ": " + windowDims[x] + s2 + "<br>";
		}
	pr (s, 300000);
	}
	
if (savedPopupElem && ai.ratioAdder>.9) {
	ai.isComplete = true;
	EventHandlers.setEventHandler (mainImage, "onload",  [popuppic_imageLoadCallback, [imgData, ai]]);
	// src must be assigned AFTER onload, or onload won't get called in ie
	mainImage.style.visibility = "hidden";
	mainImage.src = block.path + imgData[0] + "." + ((block.bigExt)?block.bigExt:block.ext);
	popuppic_displayImageAndCaption (ai);
	popuppic_removeImageAndCaptionElems (savedPopupElem, 20);
	}
else {
  ai.elem = popuppic_makeAnimElement(styleInfo, useLastPopup);
	
  // this should only be for colorizer
	// src must be assigned AFTER onload, or onload won't get called in ie
	EventHandlers.setEventHandler (mainImage, "onload",  [popuppic_imageLoadCallback, [imgData, ai]]);
	// src must be assigned AFTER onload, or onload won't get called in ie
	mainImage.style.visibility = "hidden";	
		
	mainImage.src = block.path + imgData[0] + "." + ((block.bigExt)?block.bigExt:block.ext);
		
	popuppic_popupAnim (ai.ratioAdder, ai);
	popuppic_removeImageAndCaptionElems (savedPopupElem, 20);
	}
return false;
}

function popuppic_chameleonCallback (eventType, elements, colors) {
	// this is here as an example.  In our case, it is only 
	// necessary so we can change the color of the "color"
  // text string.
  //document.title = eventType;
  switch (eventType) {
    case "move":
    		elements.idElem.style.backgroundColor = "#"+colors.hex;
        // cursor is moved on a color
        break;
    case "release":
        // mouse is clicked or released on a color, or a keystroke
        // produced a valid color
        break;
    case "cancel":
    		// hack
    		elements.idElem.style.backgroundColor = "#"+colors.hex;
        //if (elements.idElem.id == "cp-3")
          //document.getElementById("image").style.backgroundColor = "#"+colors.hex;
        // cancelled:  hexValue and rgb will be original color
    case "final":
    		elements.idElem.imgData[2] = "#"+colors.hex;
    		//elements.idElem.imgData = null;
    
    		// clicked ok, or clicked elsewhere to make widget go away
    		g_colorPickerOpen = true;
				EventHandlers.setTimerFunction ([setColorPickerClosed], 10);
        break;
        
    case "sourceloaded":
        // source code has been loaded...you may append dom element pairs
        // to elemList (array of 3 member arrays, each of which is [idElem, textElem, swatchElem])
        // if textElem or swatchElem is supplied, idElem is only used to send to the callback
        // (and does not have to be an element, can be a string or anything else)
        break;
    }
}

function setColorPickerClosed () {
g_colorPickerOpen = false;
}