﻿//GLOBAL VARIABLES:

var offset = 0;
var scrapbookslength;
var currentPosition;
var showcurrent = false;
var onview;
var selectPosition;
var currentkey = getQueryVariable("scrapbook");
var currentID = currentkey;
var emclear = 0;
var scrapbookPage = 1;

//these next two are to fix the IE6 resizing bug
var imagesToResize = new Array();

//Detect IE for timing issues
var isIE6 = false;
var isIE7 = false;
if (navigator.appVersion.indexOf("MSIE") != -1) {
	temp = navigator.appVersion.split("MSIE");
	version = parseFloat(temp[1]);
	if (version > 0 && version < 7.0) //NON IE browser will return 0
		isIE6 = true;
	else if (version >= 7.0)
		isIE7 = true;
}

//alert(sb_key);

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	} 
	//alert('Query Variable ' + variable + ' not found');
}


//------------------------------------------------------------------------------
// used to scroll thru scrapbooks within a visitor/museum category
function categoryScroll(id,direction) {

	numScrapBooks 		= $(id + "_scrapbookCount").innerHTML;
	minMargin 			= (numScrapBooks-4)*(-130);
	currentMarginLeft 	= $(id).style.marginLeft;
	currentMarginLeft 	= currentMarginLeft.replace("px","");

	if (direction == "right") {
		newMarginLeft = currentMarginLeft - 130;
	} else {
		newMarginLeft = Number(currentMarginLeft) + Number(130);
	}

	//alert(currentMargin + " | " + indexLastSpace + " | " + indexPx + " | " + currentMarginLeft);
	//alert(currentMarginLeft + " > " + newMarginLeft);

	$(id).style.marginLeft = newMarginLeft + "px";

	// disable the left or right arrow if the new left margin value is at the max or min value
	if (newMarginLeft <= minMargin) {
		$(id + "_right").style.visibility = "hidden";
	} else {
		$(id + "_right").style.visibility = "visible";
	}
	if (newMarginLeft >= 0) {
		$(id + "_left").style.visibility = "hidden";
	} else {
		$(id + "_left").style.visibility = "visible";
	}
}


//------------------------------------------------------------------------------
//Highlights and Loads Scrapbook
function myscrapbookSelect(type, position, id) {
	if (getQueryVariable("msg") && emclear > 0) {
		$("errmsg").innerHTML = "";
	}
	else {
		emclear++;
	}
	if (position != "") {
		$("myscrapbook" + position).style.backgroundImage='url(images/previewbox_active.gif)';
		currentPosition = position;
		currentID = id;
	}
}



//------------------------------------------------------------------------------
//Redirects to object page
function objectSelect(url) {
	window.location = url;
}

//Redirects to page and passes object query string
function scrapbookView(url, id) {
	url = url + "?object=" + id;
	window.location = url;
}



//------------------------------------------------------------------------------
function collectObjects() {
	var alerttxt = "You have collected the following items: \n \n";
	for(x=0; x < document.forms.collectform.collect.length; x++)
		{
		if(document.forms.collectform.collect[x].checked)
			{
			alerttxt += document.forms.collectform.collect[x].value + "\n";
			}
		}
	if (alerttxt == "You have collected the following items: \n \n")
		{
		alert("You have not selected any artworks to collect.");
		}
	else
		{
		alert(alerttxt);
		document.forms.collectform.submit();
		}
}



//-------------------------------------------------------------------------------
//OTHER JAVASCRIPT FUNCTIONS

//DATE
function getms() {
	var d = new Date();
	return d.getMilliseconds();
}

//CONFIRMATION
function deletescrapbook(delurl) {
    var answer = confirm("Are you sure you want to delete this scrapbook?")
     if (answer){
     	window.location = delurl;
     }
}

//Reorder (used on mobject.cfm)
function reorder(selection) {
	if (selection.options[selection.selectedIndex].value != "") {
		var answer = confirm("Do you want to reorder this scrapbook artwork?")
		if (answer) {
			window.location = "reorderobject.cfm?" + selection.options[selection.selectedIndex].value;
		}
	}
}

//Move to Scrapbook (used on mobject.cfm)
function movetoscrapbook(selection) {
	var answer = confirm("Do you want to add this artwork to the desired scrapbook?")
	if (answer) {
  		// window.location = "moveobject.cfm?" + selection.options[selection.selectedIndex].value;
		new Ajax.Request('moveobject.cfm', {
			method: 'get',
			parameters: selection.options[selection.selectedIndex].value + '&passive_response=true',
			onSuccess: function() {
				alert('The object has been added to your scrapbook.')
			}
		});
	}
}

//Move to Scrapbook (used on mscrapbook.cfm drag + drop)
function movetoscrapbook2(string) {
	var answer = confirm("Do you want to add this artwork to the desired scrapbook?")
	if (answer) {
  		window.location = "moveobject.cfm?" + string;
	}
}

function removeobject(obj,scrap) {
	var answer = confirm("Do you want to remove this artwork from this scrapbook?")
	if (answer) {
  		window.location = "removeobject.cfm?scrapbook=" + scrap + "&objectID=" + obj;
	}
}

//-----------------------------------------------------------------------------------

function selectScrapbook(scrapbook) {
	var selected = selectedScrapbook();
	if (selected)
		Element.removeClassName(selected, 'selected_scrapbook');
	if (scrapbook != 'not_used') Element.addClassName(scrapbook, 'selected_scrapbook');
}

function selectedScrapbook() {
	var selected = $('myscrapbooks').select('.selected_scrapbook');
	if (selected.length > 0)
		return selected[0];
	else
		return null;
}

function slideScrapbooks(dir,container_id_base) {
	var suffix = arguments[2] ? '_' + arguments[2] : '';
	var container = $(container_id_base + suffix);
	if (dir == 'left' && container.position + 2 < container.num_scrapbooks) {
		container.position = container.position + 1;
		new Effect.MoveBy(container,0,-130,{duration:0.4});
	} else if (dir == 'right' && container.position - 1 > 0) {
		container.position = container.position - 1;
		new Effect.MoveBy(container,0,130,{duration:0.4});
	}
	$('rightarrow' + suffix).style.visibility = (container.position + 2 == container.num_scrapbooks) ? 'hidden' : 'visible';
	$('leftarrow' + suffix).style.visibility = (container.position == 1) ? 'hidden' : 'visible';
}

var doing_update = false;
function updateScrapbook(draggable, scrapbook) {
	doing_update = true;
	var draggableIndex = draggable.id.match(Sortable.SERIALIZE_RULE)[1];
	var oldsb = Try.these(
		function() { return selectedScrapbook().id.match(Sortable.SERIALIZE_RULE)[1]; },
		function() { return 0; }						
	);
	var newsb = scrapbook.id.match(Sortable.SERIALIZE_RULE)[1];
	var objID = $('object_' + draggableIndex + '_id').firstChild.nodeValue;
	var objURL = $('object_' + draggableIndex + '_url').firstChild.nodeValue;
	Droppables.remove($(scrapbook));
	new Ajax.Updater($(scrapbook),'moveobject.cfm', {
		method: 'get',
		asynchronous: true,
		evalScripts: true,
		insertion: Element.replace,
		parameters: 'oldsb='+oldsb+'&newsb='+newsb+'&objectID='+objID+'&imageURL='+objURL,
		onSuccess: function(request) {
			flash('errmsg','This artwork has been added to your scrapbook.');
			doing_update = false;
		}
	});
}

function updateScrapbookObjectOrder() {
	var objIndex = dragObj.id.match(Sortable.SERIALIZE_RULE)[1];
	var newIndex = Sortable.sequence('scrapdisplay').indexOf(objIndex) + 1;
	var objID = $('object_' + objIndex + '_id').firstChild.nodeValue;
	var objOrder = $('object_' + objIndex + '_order').firstChild.nodeValue;
	var newOrder = $('object_' + newIndex + '_order').firstChild.nodeValue;
	new Ajax.Request('reorderobject.cfm', {
		method: 'get',
		parameters: 'scrapbook=' + currentID + '&objectID=' + objID + '&oldOrder=' + objOrder + '&newOrder=' + newOrder + '&page=' + scrapbookPage,
		onSuccess: function() { flash('errmsg','Your artworks have been reordered.'); }
	});
}

// renders a temporary note inside an element
function flash(el,text) {
	Element.update($(el),'<span>' + text + '</span>&nbsp;');
	setTimeout("Effect.Fade($('" + el + "').firstChild,{duration: 0.5})",2000);
}


var dragObj;
function loadScrapbook() {
	Sortable.create('scrapdisplay', {
		tag:'div',
		only:'scrapobject',
		constraint:false,
		containment:['scrapdisplay','#myscrapbooks'],
		overlap:'horizontal',
		scroll:window,
		dropOnEmpty:true,
		handle:'scrapobjectimg',
		onChange: function(obj) {dragObj = obj;},
		onUpdate:updateScrapbookObjectOrder,
		reverteffect: function(element, top_offset, left_offset) {
			var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
			new Effect.Move(element, {
				x: -left_offset,
				y: -top_offset,
				delay: doing_update ? 0.6 : 0.0,
				duration: dur,
				queue: {scope:'_draggable', position:'end'}
			});
		}
	});
	$$('div.scrapobjectimg img').each(function(el) {
		sizeScrapbookImage(el, 120, 97);
	});
}

function sizeScrapbookImage(img, boundW, boundH) {
	//IE6 can't call its own onload events at the right time so we have to hold its hand.
	if (isIE6 && img != null) {
		//save a reference to the image so we can resize it in a sec.
		var imgIndex = imagesToResize.push(img) - 1;
		setTimeout("actuallySizeScrapbookImage(imagesToResize[" + imgIndex + "], " + boundW + ", " + boundH + ")", 100);
	}
	else {
		actuallySizeScrapbookImage(img, boundW, boundH);
	}
}

function actuallySizeScrapbookImage(img, boundW, boundH) {
	var imgVPad = 0;
	var imgHPad	= 0;
	var imgW = img.width;
	var imgH = img.height;
	var imgR = imgW/imgH;
	var boundR = boundW/boundH;
	if (imgR > boundR && imgW >= boundW - 2) {
		imgW = boundW - 2;
		imgH = parseInt(imgW/imgR);
		img.width = imgW;
		img.height = imgH;
	} else if (imgR <= boundR && imgH >= boundH - 2) {
		imgH = boundH - 2;
		imgW = parseInt(imgH*imgR);
		img.width = imgW;
		img.height = imgH;
	}
	// center image vertically
	if (imgH <= (boundH - 2) && imgH != 0) {
		imgVPad = parseInt((boundH - imgH)/2);
		imgVPad = imgVPad + 'px';
		img.style.marginTop = imgVPad;
	}
	img.style.visibility = 'visible';
}



