


<!-- 
// declare the variables introduced by ajax loads
var prods;	
var selects;
var isOpen = true;
var isLooks= true;
var lock=false;

var libraryImageBase="";
var linkURLBase="";
var catelogImageBase="";

function Container(){
	this.selected=new Array();
	this.products=new Array();
}
function Product(imagePath,key){
	this.IMAGE=imagePath;
	this.KEY=key;
	this.skus=new Array();
}
function Sku(group_id,name,price,sku_id,color_code,color_description,size,size_description,width,width_description){
	this.group_id=group_id;
	this.name=name;
	this.price=price;
	this.sku_id=sku_id;
	this.color_code=color_code;
	this.color_description=color_description;
	this.size=size;
	this.size_description=size_description;
	this.width=width;
	this.width_description=width_description;
}
/* this function populates the dropdowns
	usage:
		obj.populateDropdowns("[string stage]"); 
	parms:
		stage="init" (reset dropdowns)
		stage="widths" (after selecting widths) 
*/
Container.prototype.populateDropdowns = function(stage) {
	for (i = 0; i <this.products.length; i ++){	
		var prod_id=this.products[i].KEY;	
		var widthDDID = "width_"+prod_id;
		var widthDD = $(widthDDID);
		var sizeDDID = "size_"+prod_id;
		var sizeDD = $(sizeDDID);
		var checkBX = $("prodSelected_"+prod_id); 
		var vbox = prod_id;
		if 	(this.products[i].skus.length<1) {
			widthDD.hide();
			sizeDD.disable();
			$(vbox).update("So Hot It's Sold Out!");
			checkBX.disable();
			continue;
			}
		widthDD.enable();

		if (stage=="widths") { 
			this.clear_dropdown(widthDD);
		}
		if (stage=="init") { 			
			this.clear_dropdown(sizeDD);
			this.clear_dropdown(widthDD);
		}
		for (j = 0; j < this.products[i].skus.length; j ++) 
		{
			if(this.products[i].skus[j])
			{
				if (stage=="init") this.set_item(this.products[i].skus[j], sizeDD);
				desc=this.products[i].skus[j].size_description;
				w_desc=this.products[i].skus[j].width_description;
				if(desc!= '1 SIZE' && w_desc!="")
				{
					this.set_item(this.products[i].skus[j], widthDD);
				}
			}
		}
 		if(!this.products[i].hasWidth)
 		{
 			widthDD.hide();
 		}
 		if(!this.products[i].hasSize)
   		{
			sizeDD.hide();
   		}
		if(widthDD.options.length == 0)
		{
			if (stage=="init"){
				widthDD.hide();
			} else {
				widthDD.options[0]=new Option('-N/A-','');
			}
		}	
		if 	(widthDD.options.length<=1) {
			widthDD.disable();
		} else {
			widthDD.options[widthDD.options.length]=new Option('-WIDTH-','');
			this.sort_dropdown(widthDD);	
			widthDD.options.selectedIndex = 0;
		}
		if (stage=="init"){
			if 	(sizeDD.options.length==1) {
				sizeDD.disable();
			} else {
				sizeDD.options[sizeDD.options.length]=new Option('-SIZE-','');
				this.sort_dropdown(sizeDD);
				sizeDD.options.selectedIndex = 0;
			}
			// auto check box if only 1 option
			if(widthDD.options.length<=1&&sizeDD.options.length<=1) checkBX.checked=true;
		}
		//auto check box if selections were made.
		if((widthDD.options.length<=1||widthDD.options.selectedIndex>0)&&(sizeDD.options.length<=1||sizeDD.options.selectedIndex>0)) 
			checkBX.checked=true;
		else 
			checkBX.checked=false;
	}
	if (BrowserDetect.browser == "Netscape" && BrowserDetect.version < 7.2){			
		if (sizeDD.style.display!="none"){
			sizeDD.hide();
			sizeDD.show();
			sizeDD.disable();
			sizeDD.enable();
		}
		if (widthDD.style.display!="none"){
			widthDD.hide();
			widthDD.show(); 
			widthDD.disable();
			widthDD.enable();
		}			
	}	 
 };
/* this function is called when the selected item has changed in the dropdown*/
Container.prototype.changeSelect = function (frmElmnt){
		var arrId=this.split_name(frmElmnt);
	 	var type = arrId[0];
		var product_id= arrId[1];
		var product = this.get_product(product_id);	 
		var sVal=frmElmnt.getValue();	
		$(product_id).bgColor ='';
		if(type=="size"){
			var singleProd=Object.clone(prods)
			singleProd.products=new Array();
			singleProd.products[0]=Object.clone(product);
			// get skus that match our selected type
		 	if (sVal!="") singleProd.products[0].skus= this.getMatchingSKUs(product, type, sVal);
		 		else singleProd.products[0].skus=this.getMatchingSKUs(product, "group_id", product_id); // just get all skus.
			/* recalc and update widths for this product */
			singleProd.populateDropdowns("widths");
		}
		if(type=="width"){
			// do nothing for now.
		}
};


/* this function is called when a row's checkbox item has changed */
Container.prototype.changeCheckbox = function (el){
};


Container.prototype.getSku = function (group_id) {
};


/* this function sets a dropdown (object) based on the product, type (the type of dropdown) , value (the value of the selected option )*/
Container.prototype.set_dropdown = function (product, object, type, value) {

	object.options.length= 1;
	
	for (j = 0; j < product.skus.length; j ++){

		switch (type){
		case "color":
		this.selected.color = value;
		if (product.skus[j].color_code == value) {
		this.set_item (product.skus[j], object)
			
		}
		break;
		case "width":
		this.selected.width = value;
		if (product.skus[j].width == value) {
		this.set_item (product.skus[j], object)
			
		}
		
		break;
		case "size":
		this.selected.size = value;
		if (product.skus[j].size == value) {
		this.set_item (product.skus[j], object)
			
		}
	
		break;
		}
	}
  this.sort_dropdown(object);
};
Container.prototype.clear_dropdown = function (selectbox)
{
	var i;
	for(i=selectbox.options.length-1;i>=0;i--)
	{
	selectbox.remove(i);
	}
};
/* this function sets a single option for the dropdown (object) and sku*/
Container.prototype.set_item = function (sku, object)
{
 var type = this.split_name(object)[0];
 switch (type){
 	case "size":

	if (! this.in_select(sku.size , object.options)&&sku.size!=""){
				object.options[object.options.length] = new Option(sku.size_description , sku.size); 
				//alert('adding:'+sku.size);
			}
		break;
		
	case "width":

	if (! this.in_select(sku.width , object.options)&&sku.width!=""){
				object.options[object.options.length] = new Option(sku.width_description , sku.width); 
			}	
			break;
	case "color":	

			if (! this.in_select(sku.color_code , object.options&&sku.color_code!="")){
				object.options[object.options.length] = new Option(sku.color_description , sku.color_code); 
			}
			}
};


/* this function tests if the value is already in the list of options */
Container.prototype.in_select = function (needle, options) {
	var n = options.length;
	for (var i=0; i<n; i++) {
		if (options[i].value==needle) {
			return true;
		}
	}
	return false;
};


Container.prototype.sort_dropdown = function (obj){
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
// modified by jeremy dill to sort according to an array.
	Array.prototype.findIndex = function(value){
			var ctr = "";
			for (var i=0; i < this.length; i++) {
				// use === to check for Matches. ie., identical (===), ;
				if (this[i] == value) {
					return i;
				}
			}
		return ctr;
	};
	var sizesSML= new Array("-SIZE-", "XS", "T", "S", "SML", "SM", "M", "MED","ML", "L", "LRG", "XL");
	function hasOptions(obj){if(obj!=null && obj.options!=null){return true;}return false;}
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	//SORT ACCORDING TO SIZESSML ARR
	o = o.sort( 
		function(a,b) {
			//COMPARES INDEX OF VALUE IN ARRAY
			if (sizesSML.findIndex(a.text+"") < sizesSML.findIndex(b.text+"")) { return -1; }
			if (sizesSML.findIndex(a.text+"") > sizesSML.findIndex(b.text+"")) { return 1; }
			//CATCHALL FOR NUMERIC SIZES--NOT IN ARRAY
			if (a.value < b.value) { return -1; }
			if (a.value > b.value) { return 1; }
			return 0;
			}
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	}
};

 /* just a simple helper function helps to get the type of the dropdown */
Container.prototype.split_name = function (frmElmnt)
{
	return frmElmnt.id.split("_");
};


/* returns the product given pid */
Container.prototype.get_product = function (pid)
{

	 for (i = 0; i < this.products.length; i ++)
	 {
		if  (pid == this.products[i].KEY)
		return this.products[i];
	 }
}

/* returns the skus where the property has a matching value */
Container.prototype.getMatchingSKUs = function (prod, propertyName, value, skuArray)
{
	var skus;
	if(skuArray == null) {
		skus = prod.skus;
	}
	else {
		skus = skuArray;
	}
	var listOfSkus = new Array();
	var skuCount=0;
	for (i = 0; i < skus.length; i ++) {
		var sku = skus[i];

		if(sku)
		{
			if (sku[propertyName] == value) {
				listOfSkus[skuCount] = sku;
				skuCount++;
			} else {
			//	$('debugmsg').innerHTML+='didnt add sku='+sku.sku_id+'<br>';
			}
		}
	}
	//$('debugmsg').innerHTML+=
	return listOfSkus;
}
function pageLoader() {
	var lookId = 0;
	var LOOKBOOK_QUERY_KEY = "lookId"
	libraryImageBase = $('defaultImgURL').src.replace("images/spacer.gif","");
	catelogImageBase = libraryImageBase.replace('Library', 'catalog');
	//alert($('lookBookJSON').value);
	var x = $('lookBookJSON').value;

	objImages.init(x, libraryImageBase, 15);

	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] == LOOKBOOK_QUERY_KEY) {
			for(var i = 0; i < objImages.images.length; i++){
				if(objImages.images[i].id == pair[1]){
					lookId = i;
					break;
				}
			}
		}
	}

	for(var lks = 0; lks < objImages.images.length; lks++)
	{
		for(var prds=0; prds<objImages.images[lks].products.length; prds++)
		{
			objImages.images[lks].products[prds].hasSize = true;
			objImages.images[lks].products[prds].hasWidth = true;
			objImages.images[lks].products[prds].pid += "-"+objImages.images[lks].products[prds].color;
			for(var sks=0; sks<objImages.images[lks].products[prds].skus.length; sks++)
			{
				if(!objImages.images[lks].products[prds].skus[sks].size)
				{
					objImages.images[lks].products[prds].hasSize = false;
					objImages.images[lks].products[prds].skus[sks].size = "010";
					objImages.images[lks].products[prds].skus[sks].size_description = "10";
				}
				if(!objImages.images[lks].products[prds].skus[sks].width)
				{
					objImages.images[lks].products[prds].hasWidth = false;
					objImages.images[lks].products[prds].skus[sks].width = "H";
					objImages.images[lks].products[prds].skus[sks].width_description = "H";
				}
			}
		}
	}

	setTimeout("startLook(" + lookId + ")",100);
	//startLook(0);
	
}
function buy()
{
if (!lock){
	if (isOpen && !isLooks)
	{
		hideDiv('div_container', .01, .3);
		setClass ('div_btns', "LeftOff");
		isOpen = false;
	}
	else
	{
		Element.update('div_buy', $('ajax_loading').innerHTML);
		getBuyLookContent($('div_buy'));
		isOpen = true;
		isLooks= false;
		$('div_buy').className="over";
		$('div_thumbs').className="under";
		toggleFold('div_container', .1, .6);
		setClass ('div_btns', "RightBuyClose");
	}
}
}
function looks()
{
	if (!lock)
	{
		if (isOpen && isLooks)
		{
			hideDiv('div_container', .01, .3);
			setClass ('div_btns', "LeftOff");
			isOpen = false;
		}
		else
		{
			Element.update('div_buy', '');
			$('div_buy').className="under";
			$('div_thumbs').className="over";
			toggleFold('div_container', .1, .6);
			isLooks = true;
			isOpen = true;
			setClass ('div_btns', "RightLookClose");
		}
	}
}

function moveNext()
{
	if (isOpen)
	{
		hideDiv('div_container', .01, .3);
		setClass ('div_btns', "LeftOff");
		isOpen = false;
	}
	objImages.navigateImage(1);
}

function movePrevious()
{
	if (isOpen)
	{
		hideDiv('div_container', .01, .3);
		setClass ('div_btns', "LeftOff");
		isOpen = false;
	}
	objImages.navigateImage(-1);
}
function startLook(id)
{
	isOpen= false;
	objImages.setLargeImage(id);
	hideFast('div_container');
	$('shellQV').style.visibility = '';
	//$('mainQV').show();
	//setClass ('div_btns', "LeftOff");
    	
	setTimeout("looks()",500);

	var looksC=0;
	var prodsC=0;
	var skusC=0;
	for(looksC=0; looksC<objImages.images.length; looksC++)
	{
		prodsC=0;
		for(prodsC=0; prodsC<objImages.images[looksC].products.length; prodsC++)
		{
			skusC=0;
			var myArray = [];
			for(skusC=0; skusC<objImages.images[looksC].products[prodsC].skus.length; skusC++)
			{
				if(objImages.images[looksC].products[prodsC].skus[skusC].availability != "NOT_AVAILABLE")
				{
					myArray.push(objImages.images[looksC].products[prodsC].skus[skusC]);
				}
			}
			objImages.images[looksC].products[prodsC].skus = myArray;
			myArray = null;
		}
	}
}

function getBuyLookContent(domElement)
{
	var currentLookProds = objImages.images[objImages.currentImage].products;
	var numOfProds = objImages.images[objImages.currentImage].products.length;
	prods = new Container();
	var i=0;
	for(i=0; i<currentLookProds.length; i++)
	{
		//prods.products[i]= new Product("http://images.ninewest.com/images/nw/product/PG.NWPAPOOSE.MEDRESU.CS.jpg",currentLookProds[i].pid)
		prods.products[i]= new Product(currentLookProds[i].image,currentLookProds[i].pid);
		if(currentLookProds[i].skus.length > 0)
		{
 			prods.products[i].hasWidth = currentLookProds[i].hasWidth;
 			prods.products[i].hasSize = currentLookProds[i].hasSize;
			var ii = 0;
			for(ii=0; ii<currentLookProds[i].skus.length; ii++)
			{
				if(currentLookProds[i].skus[ii].availability != "NOT_AVAILABLE")
				{
					prods.products[i].skus[ii]=new Sku(currentLookProds[i].pid,currentLookProds[i].skus[ii].name,currentLookProds[i].skus[ii].price,currentLookProds[i].skus[ii].sku,currentLookProds[i].skus[ii].color_code,currentLookProds[i].skus[ii].color_description,currentLookProds[i].skus[ii].size,currentLookProds[i].skus[ii].size_description,currentLookProds[i].skus[ii].width,currentLookProds[i].skus[ii].width_description);
				}
			}
		}
	}

	var buyHTML = '<div id="buy_look"><form id="buylookform">';

	if(numOfProds > 0)
	{
		buyHTML += '<div id="description">Select the item and sizing info below to add the items to your bag.</div>';
	}
	buyHTML += '<div class="scroller"><table><tr>';
	if(numOfProds > 0)
	{
		buyHTML += '<th>Item</th><th>Name</th><th>Price</th><th colspan="2">Options</th><th>Select</th></tr>';
		var prodColor = "";
		var prodName ="";
		var prodPrice="";
		var prodImage="";

		var errorIMG = "this.src='"+libraryImageBase+"images/lookbook/lookboo-error-image.jpg';";

		for(i=0; i<currentLookProds.length; i++)
		{
			prodColor = currentLookProds[i].color_description;
			prodName = currentLookProds[i].name;

			if(currentLookProds[i].skus.length > 0){
				prodPrice = currentLookProds[i].skus[0].price;
				if(prodPrice.indexOf(".") == -1){
					prodPrice += ".00";	
				}
			}
			prodImage = currentLookProds[i].image;
			buyHTML += '<tr id="'+currentLookProds[i].pid+'_row"><td class="desc"><a href="'+linkURLBase+'Product-Show?pid='+currentLookProds[i].pid.split('-')[0]+'"><img onError="'+errorIMG+'" src="'+catelogImageBase+prodImage+'" /></a><br /><span class="prodColor">'+prodColor+'</span></td><td class="name"><span class="prodName">'+prodName+'</span></td><td class="w54"><span class="prodPrice">$'+prodPrice+'</span></td><td class="w170" id="'+currentLookProds[i].pid+'"><select id="size_'+currentLookProds[i].pid+'" > </select> <select id="width_'+currentLookProds[i].pid+'" > </select></td><td class="w94"><a href="'+linkURLBase+'Product-Show?pid='+currentLookProds[i].pid.split('-')[0]+'">More options</a></td><td class="w54"><label for ="prodSelected_'+currentLookProds[i].pid+'" class="checkWrap"><input id="prodSelected_'+currentLookProds[i].pid+'" type="checkbox" value="false" /></label></td></tr>';
			prodColor = "";
			prodName ="";
			prodPrice="";
			prodImage="";
		}
	} else {
		buyHTML += '<p class="message_b">Coming Soon...</p>';
		buyHTML += '<p class="message_a">We are sorry.  The products for this look are not currently available.  Please try again later.</p>';
	}
	buyHTML += '</tr></table></div>';

	buyHTML += '<div id="addToCartMessage" class="messaging errb">&nbsp;</div>';
	if(numOfProds > 0)
		buyHTML += '<div id="lookbookButtons">';
	else
		buyHTML += '<div id="lookbookButtons" style="display:none">';

	buyHTML += '<img id="lookbookAddToBag" class="lookbookAddToBag" src="'+libraryImageBase+'images/lookbook/button_add_to_bag.gif" alt="add to bag" />&nbsp;&nbsp;';
	buyHTML += '<img style="visibility:hidden;" id="lookbookAddToCloset" class="lookbookAddToBag" src="'+libraryImageBase+'images/lookbook/button_add_to_my_closet.gif" alt="add to closet"  /></div></form></div>';
	
	Element.update(domElement,buyHTML);

	// populate dropdowns
	prods.populateDropdowns("init");

	// bind click handlers to buttons
	Event.observe($('lookbookAddToBag'), 'click', function() { addToCart(1); });
	Event.observe($('lookbookAddToCloset'), 'click', function() { addToCart(2); });

	// bind change handlers to selects and checkboxes
	var selectElements = Form.getElements('buylookform');
	var selectsArray = $A(selectElements);
	selectsArray.each (
		function(value, index) 
		{
			if(value.tagName == 'SELECT')
			{
				Event.observe(value,'change',function(event) 
				{
					var el=Event.element(event);
					prods.changeSelect(el);
				})
			}
			else if(value.type == 'checkbox')
			{
    			Event.observe(value,'change',function(event) 
				{
					var el=Event.element(event);
					prods.changeCheckbox(el);
				})
			}
		}
	);
	if (BrowserDetect.browser == "Safari") 
	{
		// fix safari 1.3.2 rendering issue with buttons
		$('lookbookAddToBag').makeClipping();
		$('lookbookAddToCloset').makeClipping();
	}
}

function addToCart(cartType)
{ 
if (!lock){
  //var url = 'http://int.us.jag.demandware.net/on/demandware.store/Sites-ninewest-Site/default/Cart-AddMultipleProducts?';
  var url = 'Cart-AddMultipleProducts?';
  // var url = some multi add to cart controler
  var groups = new Array();
  var names= new Array();
  var prices= new Array(); 
  var skus = new Array();
  var quantities = new Array();
  var sources = new Array();
 // todo get skus from form
  var form = $('buylookform');
  var checks = form.getInputs('checkbox');
  var productSelected = false;
  var selectCount=0;
  var errorCheck=false;
  checks.each( function(el) {if(el.checked) {productSelected = true} });  
  if(!productSelected)
  {
  	$('addToCartMessage').innerHTML = "Please select a product.";
  	return false;
  } else {
  //validate checkboxes and build product arrays for url
   	checks.each( function(el) {
   	 if(el.checked) {
  			var arrId=prods.split_name(el);
 		 	var product_id= arrId[1];
		 	var product = prods.get_product(product_id);
		 	var wVal=$("width_"+product_id).getValue();
		 	var widthDD=$("width_"+product_id);
		 	var sVal=$("size_"+product_id).getValue();
			var sTxt=$("size_"+product_id).options[$("size_"+product_id).selectedIndex].text;
			if ( ( sVal!=""&&(wVal!=""||widthDD.style.display=="none") ) || sTxt=="1 SIZE"){			
					//var skuFunnel=new Array();
					var skuFunnel=product.skus.clone();
						// get skus that match our size
				 	skuFunnel= prods.getMatchingSKUs(product, "size", sVal, skuFunnel);
					// get skus that match our width
				 	if (widthDD.style.display!="none") skuFunnel= prods.getMatchingSKUs(product, "width", wVal, skuFunnel);
				 	if (skuFunnel.length==1){
				 		groups[selectCount]=skuFunnel[0]['group_id'];
				 		names[selectCount]=skuFunnel[0]['name'];
				 		prices[selectCount]=skuFunnel[0]['price'];
				 		skus[selectCount]=skuFunnel[0]['sku_id'];
				 		quantities[selectCount]="1";
				 		sources[selectCount] = objImages.images[objImages.currentImage].id;
				 		selectCount++; //advance counter
				 	} else {
				 	/* something was wrong with sku.  Restart and warn. */
						$('addToCartMessage').innerHTML = "There is a problem with one of your selections.  Please contact customer service.";
						$(product_id).bgColor ='yellow';
						errorCheck=true;
					}
				} else {
				/* something was wrong with selections.  Restart and warn. */
					//prods.populateDropdowns("init");
					$('addToCartMessage').innerHTML = "Please select a size and width for each product selected.";
					$(product_id).bgColor ='yellow';
					errorCheck=true;
				}
		}
	});
	if (!errorCheck){
 	 // continue with add to cart/closet
	  // build url for add and set hitbox vars
	var itemsThatAreAdded = groups.length;
	 for (i = 0; i <groups.length; i ++){	
		if(i==0){
		 url += 'groups['+i+']=' + groups[i];

		} else {
		 url += '&groups['+i+']=' + groups[i];

		}
		url += '&skus['+i+']=' + skus[i];
		url += '&quantities['+i+']=' + quantities[i];
		url += '&sources['+i+']=' + sources[i];
	  }
	  url += '&cartType=' + cartType
	  url += '&decoParam=blank.jsp';  // this has to be on the end of the url
	

	 // return false;
	  
	  // make ajax call
	   lockAndLoad('addToCartMessage','<span><img src="'+libraryImageBase+'images/lookbook/ajax-loader_sm.gif" />&nbsp;Adding...</span>');
	  var request = new Ajax.Request( url, 
	    { 
	      method:'get',
	      onSuccess: function(transport)
	      {	      
	        var success = request.transport.responseText.indexOf('successful cart add') > -1;
	        if(success)
	        {
		        if(cartType==1){
		       		msg = 'The items you selected were added to your bag.';
					var checkOutLink = $('shoppingBag').getElementsByTagName('a')[0];
		      	 	var checkOutLinkText = checkOutLink.innerHTML;

					var checkOutCount = checkOutLinkText.substring(checkOutLinkText.lastIndexOf('(')+1,checkOutLinkText.lastIndexOf('item'));

					var newCount = parseInt(checkOutCount) + itemsThatAreAdded;
					if(newCount == 1)
						checkOutLink.innerHTML = "Checkout ("+newCount+" item)";
					else
						checkOutLink.innerHTML = "Checkout ("+newCount+" items)";
				}
				if(cartType==2){
					msg = 'The items you selected were added to your closet.';
					//updateClosetCount('http://www.ninewest.com/n/staticPage.s?path=hub/&fName=closetItemCount&decoparam=blank.jsp');
				} 
				$('addToCartMessage').innerHTML = msg;	
	        } else {
	         $('addToCartMessage').innerHTML = "Error 24:  Please Try Again.  ";
	         }
	         // RESET FORM
	         checks.each( function(el) {if(el.checked) {el.checked=false;} }); 
	         unlock();
	         prods.populateDropdowns("init");
	      },
	      onFailure: function()
	      {
	       $('addToCartMessage').innerHTML = "Error 25:  Please Try Again";
	       unlock();
	      }
	    }
	  );
/* not sure what this code was for.
	  if(request.transport.responseText)
	  {
	    var rtext = request.transport.responseText.strip();
		return rtext;
	  }
*/
	} //close if (!errorCheck){
 } //close else
}
} //close function


function btnsBgLB(source, state)
{
	var className;
	var newClass="";
	var lookBuy;

	if (!isOpen)
		className="Left";
	else
		className="Right";

	if (state=="on") //mouse over
	{
		if (source=="looks")
			lookBuy = "Look";
		else
			lookBuy = "Buy";


	if (className== "Right") //if expanded
	{
		if (($('div_thumbs').className=="over") &&(source=="looks"))
			newClass="Close";
		if (($('div_thumbs').className=="under") &&(source=="buy"))
			newClass = "Close";
	}
	setClass('div_btns', className+lookBuy+newClass);

	}
	else // mouseout

	{

	if (className=="Right") // if already expanded
	{
		if ($('div_thumbs').className=="over")
			lookBuy = "Look";
		else
			lookBuy = "Buy";
		setClass('div_btns', "Right" +lookBuy+"Close");
	}
	else
		setClass('div_btns', className+"Off");
	}
}
// script.aculo.us dragdrop.js v1.7.0, Fri Jan 19 19:16:36 CET 2007

// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if(typeof Effect == 'undefined')
  throw("dragdrop.js requires including script.aculo.us' effects.js library");

var Droppables = {
  drops: [],

  remove: function(element) {
    this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  },

  add: function(element) {
    element = $(element);
    var options = Object.extend({
      greedy:     true,
      hoverclass: null,
      tree:       false
    }, arguments[1] || {});

    // cache containers
    if(options.containment) {
      options._containers = [];
      var containment = options.containment;
      if((typeof containment == 'object') && 
        (containment.constructor == Array)) {
        containment.each( function(c) { options._containers.push($(c)) });
      } else {
        options._containers.push($(containment));
      }
    }
    
    if(options.accept) options.accept = [options.accept].flatten();

    Element.makePositioned(element); // fix IE
    options.element = element;

    this.drops.push(options);
  },
  
  findDeepestChild: function(drops) {
    deepest = drops[0];
      
    for (i = 1; i < drops.length; ++i)
      if (Element.isParent(drops[i].element, deepest.element))
        deepest = drops[i];
    
    return deepest;
  },

  isContained: function(element, drop) {
    var containmentNode;
    if(drop.tree) {
      containmentNode = element.treeNode; 
    } else {
      containmentNode = element.parentNode;
    }
    return drop._containers.detect(function(c) { return containmentNode == c });
  },
  
  isAffected: function(point, element, drop) {
    return (
      (drop.element!=element) &&
      ((!drop._containers) ||
        this.isContained(element, drop)) &&
      ((!drop.accept) ||
        (Element.classNames(element).detect( 
          function(v) { return drop.accept.include(v) } ) )) &&
      Position.within(drop.element, point[0], point[1]) );
  },

  deactivate: function(drop) {
    if(drop.hoverclass)
      Element.removeClassName(drop.element, drop.hoverclass);
    this.last_active = null;
  },

  activate: function(drop) {
    if(drop.hoverclass)
      Element.addClassName(drop.element, drop.hoverclass);
    this.last_active = drop;
  },

  show: function(point, element) {
    if(!this.drops.length) return;
    var affected = [];
    
    if(this.last_active) this.deactivate(this.last_active);
    this.drops.each( function(drop) {
      if(Droppables.isAffected(point, element, drop))
        affected.push(drop);
    });
        
    if(affected.length>0) {
      drop = Droppables.findDeepestChild(affected);
      Position.within(drop.element, point[0], point[1]);
      if(drop.onHover)
        drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
      
      Droppables.activate(drop);
    }
  },

  fire: function(event, element) {
    if(!this.last_active) return;
    Position.prepare();

    if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
      if (this.last_active.onDrop) 
        this.last_active.onDrop(element, this.last_active.element, event);
  },

  reset: function() {
    if(this.last_active)
      this.deactivate(this.last_active);
  }
}

var Draggables = {
  drags: [],
  observers: [],
  
  register: function(draggable) {
    if(this.drags.length == 0) {
      this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
      this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
      this.eventKeypress  = this.keyPress.bindAsEventListener(this);
      
      Event.observe(document, "mouseup", this.eventMouseUp);
      Event.observe(document, "mousemove", this.eventMouseMove);
      Event.observe(document, "keypress", this.eventKeypress);
    }
    this.drags.push(draggable);
  },
  
  unregister: function(draggable) {
    this.drags = this.drags.reject(function(d) { return d==draggable });
    if(this.drags.length == 0) {
      Event.stopObserving(document, "mouseup", this.eventMouseUp);
      Event.stopObserving(document, "mousemove", this.eventMouseMove);
      Event.stopObserving(document, "keypress", this.eventKeypress);
    }
  },
  
  activate: function(draggable) {
    if(draggable.options.delay) { 
      this._timeout = setTimeout(function() { 
        Draggables._timeout = null; 
        window.focus(); 
        Draggables.activeDraggable = draggable; 
      }.bind(this), draggable.options.delay); 
    } else {
      window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
      this.activeDraggable = draggable;
    }
  },
  
  deactivate: function() {
    this.activeDraggable = null;
  },
  
  updateDrag: function(event) {
    if(!this.activeDraggable) return;
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    // Mozilla-based browsers fire successive mousemove events with
    // the same coordinates, prevent needless redrawing (moz bug?)
    if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
    this._lastPointer = pointer;
    
    this.activeDraggable.updateDrag(event, pointer);
  },
  
  endDrag: function(event) {
    if(this._timeout) { 
      clearTimeout(this._timeout); 
      this._timeout = null; 
    }
    if(!this.activeDraggable) return;
    this._lastPointer = null;
    this.activeDraggable.endDrag(event);
    this.activeDraggable = null;
  },
  
  keyPress: function(event) {
    if(this.activeDraggable)
      this.activeDraggable.keyPress(event);
  },
  
  addObserver: function(observer) {
    this.observers.push(observer);
    this._cacheObserverCallbacks();
  },
  
  removeObserver: function(element) {  // element instead of observer fixes mem leaks
    this.observers = this.observers.reject( function(o) { return o.element==element });
    this._cacheObserverCallbacks();
  },
  
  notify: function(eventName, draggable, event) {  // 'onStart', 'onEnd', 'onDrag'
    if(this[eventName+'Count'] > 0)
      this.observers.each( function(o) {
        if(o[eventName]) o[eventName](eventName, draggable, event);
      });
    if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
  },
  
  _cacheObserverCallbacks: function() {
    ['onStart','onEnd','onDrag'].each( function(eventName) {
      Draggables[eventName+'Count'] = Draggables.observers.select(
        function(o) { return o[eventName]; }
      ).length;
    });
  }
}

/*--------------------------------------------------------------------------*/

var Draggable = Class.create();
Draggable._dragging    = {};

Draggable.prototype = {
  initialize: function(element) {
    var defaults = {
      handle: false,
      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, duration: dur,
          queue: {scope:'_draggable', position:'end'}
        });
      },
      endeffect: function(element) {
        var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
        new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, 
          queue: {scope:'_draggable', position:'end'},
          afterFinish: function(){ 
            Draggable._dragging[element] = false 
          }
        }); 
      },
      zindex: 1000,
      revert: false,
      scroll: false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      snap: false,  // false, or xy or [x,y] or function(x,y){ return [x,y] }
      delay: 0
    };
    
    if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
      Object.extend(defaults, {
        starteffect: function(element) {
          element._opacity = Element.getOpacity(element);
          Draggable._dragging[element] = true;
          new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); 
        }
      });
    
    var options = Object.extend(defaults, arguments[1] || {});

    this.element = $(element);
    
    if(options.handle && (typeof options.handle == 'string'))
      this.handle = this.element.down('.'+options.handle, 0);
    
    if(!this.handle) this.handle = $(options.handle);
    if(!this.handle) this.handle = this.element;
    
    if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
      options.scroll = $(options.scroll);
      this._isScrollChild = Element.childOf(this.element, options.scroll);
    }

    Element.makePositioned(this.element); // fix IE    

    this.delta    = this.currentDelta();
    this.options  = options;
    this.dragging = false;   

    this.eventMouseDown = this.initDrag.bindAsEventListener(this);
    Event.observe(this.handle, "mousedown", this.eventMouseDown);
    
    Draggables.register(this);
  },
  
  destroy: function() {
    Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
    Draggables.unregister(this);
  },
  
  currentDelta: function() {
    return([
      parseInt(Element.getStyle(this.element,'left') || '0'),
      parseInt(Element.getStyle(this.element,'top') || '0')]);
  },
  
  initDrag: function(event) {
    if(typeof Draggable._dragging[this.element] != 'undefined' &&
      Draggable._dragging[this.element]) return;
    if(Event.isLeftClick(event)) {    
      // abort on form elements, fixes a Firefox issue
      var src = Event.element(event);
      if((tag_name = src.tagName.toUpperCase()) && (
        tag_name=='INPUT' ||
        tag_name=='SELECT' ||
        tag_name=='OPTION' ||
        tag_name=='BUTTON' ||
        tag_name=='TEXTAREA')) return;
        
      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      var pos     = Position.cumulativeOffset(this.element);
      this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
      
      Draggables.activate(this);
      Event.stop(event);
    }
  },
  
  startDrag: function(event) {
    this.dragging = true;
    
    if(this.options.zindex) {
      this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
      this.element.style.zIndex = this.options.zindex;
    }
    
    if(this.options.ghosting) {
      this._clone = this.element.cloneNode(true);
      Position.absolutize(this.element);
      this.element.parentNode.insertBefore(this._clone, this.element);
    }
    
    if(this.options.scroll) {
      if (this.options.scroll == window) {
        var where = this._getWindowScroll(this.options.scroll);
        this.originalScrollLeft = where.left;
        this.originalScrollTop = where.top;
      } else {
        this.originalScrollLeft = this.options.scroll.scrollLeft;
        this.originalScrollTop = this.options.scroll.scrollTop;
      }
    }
    
    Draggables.notify('onStart', this, event);
        
    if(this.options.starteffect) this.options.starteffect(this.element);
  },
  
  updateDrag: function(event, pointer) {
    if(!this.dragging) this.startDrag(event);
    Position.prepare();
    Droppables.show(pointer, this.element);
    Draggables.notify('onDrag', this, event);
    
    this.draw(pointer);
    if(this.options.change) this.options.change(this);
    
    if(this.options.scroll) {
      this.stopScrolling();
      
      var p;
      if (this.options.scroll == window) {
        with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
      } else {
        p = Position.page(this.options.scroll);
        p[0] += this.options.scroll.scrollLeft + Position.deltaX;
        p[1] += this.options.scroll.scrollTop + Position.deltaY;
        p.push(p[0]+this.options.scroll.offsetWidth);
        p.push(p[1]+this.options.scroll.offsetHeight);
      }
      var speed = [0,0];
      if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
      if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
      if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
      if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
      this.startScrolling(speed);
    }
    
    // fix AppleWebKit rendering
    if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
    
    Event.stop(event);
  },
  
  finishDrag: function(event, success) {
    this.dragging = false;

    if(this.options.ghosting) {
      Position.relativize(this.element);
      Element.remove(this._clone);
      this._clone = null;
    }

    if(success) Droppables.fire(event, this.element);
    Draggables.notify('onEnd', this, event);

    var revert = this.options.revert;
    if(revert && typeof revert == 'function') revert = revert(this.element);
    
    var d = this.currentDelta();
    if(revert && this.options.reverteffect) {
      this.options.reverteffect(this.element, 
        d[1]-this.delta[1], d[0]-this.delta[0]);
    } else {
      this.delta = d;
    }

    if(this.options.zindex)
      this.element.style.zIndex = this.originalZ;

    if(this.options.endeffect) 
      this.options.endeffect(this.element);
      
    Draggables.deactivate(this);
    Droppables.reset();
  },
  
  keyPress: function(event) {
    if(event.keyCode!=Event.KEY_ESC) return;
    this.finishDrag(event, false);
    Event.stop(event);
  },
  
  endDrag: function(event) {
    if(!this.dragging) return;
    this.stopScrolling();
    this.finishDrag(event, true);
    Event.stop(event);
  },
  
  draw: function(point) {
    var pos = Position.cumulativeOffset(this.element);
    if(this.options.ghosting) {
      var r   = Position.realOffset(this.element);
      pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
    }
    
    var d = this.currentDelta();
    pos[0] -= d[0]; pos[1] -= d[1];
    
    if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
    }
    
    var p = [0,1].map(function(i){ 
      return (point[i]-pos[i]-this.offset[i]) 
    }.bind(this));
    
    if(this.options.snap) {
      if(typeof this.options.snap == 'function') {
        p = this.options.snap(p[0],p[1],this);
      } else {
      if(this.options.snap instanceof Array) {
        p = p.map( function(v, i) {
          return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
      } else {
        p = p.map( function(v) {
          return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
      }
    }}
    
    var style = this.element.style;
    if((!this.options.constraint) || (this.options.constraint=='horizontal'))
      style.left = p[0] + "px";
    if((!this.options.constraint) || (this.options.constraint=='vertical'))
      style.top  = p[1] + "px";
    
    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  },
  
  stopScrolling: function() {
    if(this.scrollInterval) {
      clearInterval(this.scrollInterval);
      this.scrollInterval = null;
      Draggables._lastScrollPointer = null;
    }
  },
  
  startScrolling: function(speed) {
    if(!(speed[0] || speed[1])) return;
    this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
    this.lastScrolled = new Date();
    this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  },
  
  scroll: function() {
    var current = new Date();
    var delta = current - this.lastScrolled;
    this.lastScrolled = current;
    if(this.options.scroll == window) {
      with (this._getWindowScroll(this.options.scroll)) {

        if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
          var d = delta / 1000;


          this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
        }
      }
    } else {
      this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
      this.options.scroll.scrollTop  += this.scrollSpeed[1] * delta / 1000;
    }
    
    Position.prepare();
    Droppables.show(Draggables._lastPointer, this.element);
    Draggables.notify('onDrag', this);
    if (this._isScrollChild) {
      Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
      Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
      Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
      if (Draggables._lastScrollPointer[0] < 0)
        Draggables._lastScrollPointer[0] = 0;
      if (Draggables._lastScrollPointer[1] < 0)
        Draggables._lastScrollPointer[1] = 0;
      this.draw(Draggables._lastScrollPointer);
    }
    
    if(this.options.change) this.options.change(this);
  },
  
  _getWindowScroll: function(w) {
    var T, L, W, H;
    with (w.document) {
      if (w.document.documentElement && documentElement.scrollTop) {
        T = documentElement.scrollTop;
        L = documentElement.scrollLeft;
      } else if (w.document.body) {
        T = body.scrollTop;
        L = body.scrollLeft;
      }
      if (w.innerWidth) {
        W = w.innerWidth;
        H = w.innerHeight;
      } else if (w.document.documentElement && documentElement.clientWidth) {
        W = documentElement.clientWidth;
        H = documentElement.clientHeight;
      } else {
        W = body.offsetWidth;
        H = body.offsetHeight
      }
    }
    return { top: T, left: L, width: W, height: H };
  }
}

/*--------------------------------------------------------------------------*/

var SortableObserver = Class.create();
SortableObserver.prototype = {
  initialize: function(element, observer) {
    this.element   = $(element);
    this.observer  = observer;
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onStart: function() {
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onEnd: function() {
    Sortable.unmark();
    if(this.lastValue != Sortable.serialize(this.element))
      this.observer(this.element)
  }
}

var Sortable = {
  SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
  
  sortables: {},
  
  _findRootElement: function(element) {
    while (element.tagName.toUpperCase() != "BODY") {  
      if(element.id && Sortable.sortables[element.id]) return element;
      element = element.parentNode;
    }
  },

  options: function(element) {
    element = Sortable._findRootElement($(element));
    if(!element) return;
    return Sortable.sortables[element.id];
  },
  
  destroy: function(element){
    var s = Sortable.options(element);
    
    if(s) {
      Draggables.removeObserver(s.element);
      s.droppables.each(function(d){ Droppables.remove(d) });
      s.draggables.invoke('destroy');
      
      delete Sortable.sortables[s.element.id];
    }
  },

  create: function(element) {
    element = $(element);
    var options = Object.extend({ 
      element:     element,
      tag:         'li',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'ul',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      delay:       0,
      hoverclass:  null,
      ghosting:    false,
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      this.SERIALIZE_RULE,
      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || {});

    // clear any old sortable with same element
    this.destroy(element);

    // build options for the draggables
    var options_for_draggable = {
      revert:      true,
      scroll:      options.scroll,
      scrollSpeed: options.scrollSpeed,
      scrollSensitivity: options.scrollSensitivity,
      delay:       options.delay,
      ghosting:    options.ghosting,
      constraint:  options.constraint,
      handle:      options.handle };

    if(options.starteffect)
      options_for_draggable.starteffect = options.starteffect;

    if(options.reverteffect)
      options_for_draggable.reverteffect = options.reverteffect;
    else
      if(options.ghosting) options_for_draggable.reverteffect = function(element) {
        element.style.top  = 0;
        element.style.left = 0;
      };

    if(options.endeffect)
      options_for_draggable.endeffect = options.endeffect;

    if(options.zindex)
      options_for_draggable.zindex = options.zindex;

    // build options for the droppables  
    var options_for_droppable = {
      overlap:     options.overlap,
      containment: options.containment,
      tree:        options.tree,
      hoverclass:  options.hoverclass,
      onHover:     Sortable.onHover
    }
    
    var options_for_tree = {
      onHover:      Sortable.onEmptyHover,
      overlap:      options.overlap,
      containment:  options.containment,
      hoverclass:   options.hoverclass
    }

    // fix for gecko engine
    Element.cleanWhitespace(element); 

    options.draggables = [];
    options.droppables = [];

    // drop on empty handling
    if(options.dropOnEmpty || options.tree) {
      Droppables.add(element, options_for_tree);
      options.droppables.push(element);
    }

    (this.findElements(element, options) || []).each( function(e) {
      // handles are per-draggable
      var handle = options.handle ? 
        $(e).down('.'+options.handle,0) : e;    
      options.draggables.push(
        new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
      Droppables.add(e, options_for_droppable);
      if(options.tree) e.treeNode = element;
      options.droppables.push(e);      
    });
    
    if(options.tree) {
      (Sortable.findTreeElements(element, options) || []).each( function(e) {
        Droppables.add(e, options_for_tree);
        e.treeNode = element;
        options.droppables.push(e);
      });
    }

    // keep reference
    this.sortables[element.id] = options;

    // for onupdate
    Draggables.addObserver(new SortableObserver(element, options.onUpdate));

  },

  // return all suitable-for-sortable elements in a guaranteed order
  findElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.tag);
  },
  
  findTreeElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.treeTag);
  },

  onHover: function(element, dropon, overlap) {
    if(Element.isParent(dropon, element)) return;

    if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
      return;
    } else if(overlap>0.5) {
      Sortable.mark(dropon, 'before');
      if(dropon.previousSibling != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, dropon);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    } else {
      Sortable.mark(dropon, 'after');
      var nextElement = dropon.nextSibling || null;
      if(nextElement != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, nextElement);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    }
  },
  
  onEmptyHover: function(element, dropon, overlap) {
    var oldParentNode = element.parentNode;
    var droponOptions = Sortable.options(dropon);
        
    if(!Element.isParent(dropon, element)) {
      var index;
      
      var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
      var child = null;
            
      if(children) {
        var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
        
        for (index = 0; index < children.length; index += 1) {
          if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
            offset -= Element.offsetSize (children[index], droponOptions.overlap);
          } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
            child = index + 1 < children.length ? children[index + 1] : null;
            break;
          } else {
            child = children[index];
            break;
          }
        }
      }
      
      dropon.insertBefore(element, child);
      
      Sortable.options(oldParentNode).onChange(element);
      droponOptions.onChange(element);
    }
  },

  unmark: function() {
    if(Sortable._marker) Sortable._marker.hide();
  },

  mark: function(dropon, position) {
    // mark on ghosting only
    var sortable = Sortable.options(dropon.parentNode);
    if(sortable && !sortable.ghosting) return; 

    if(!Sortable._marker) {
      Sortable._marker = 
        ($('dropmarker') || Element.extend(document.createElement('DIV'))).
          hide().addClassName('dropmarker').setStyle({position:'absolute'});
      document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
    }    
    var offsets = Position.cumulativeOffset(dropon);
    Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
    
    if(position=='after')
      if(sortable.overlap == 'horizontal') 
        Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
      else
        Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
    
    Sortable._marker.show();
  },
  
  _tree: function(element, options, parent) {
    var children = Sortable.findElements(element, options) || [];
  
    for (var i = 0; i < children.length; ++i) {
      var match = children[i].id.match(options.format);

      if (!match) continue;
      
      var child = {
        id: encodeURIComponent(match ? match[1] : null),
        element: element,
        parent: parent,
        children: [],
        position: parent.children.length,
        container: $(children[i]).down(options.treeTag)
      }
      
      /* Get the element containing the children and recurse over it */
      if (child.container)
        this._tree(child.container, options, child)
      
      parent.children.push (child);
    }

    return parent; 
  },

  tree: function(element) {
    element = $(element);
    var sortableOptions = this.options(element);
    var options = Object.extend({
      tag: sortableOptions.tag,
      treeTag: sortableOptions.treeTag,
      only: sortableOptions.only,
      name: element.id,
      format: sortableOptions.format
    }, arguments[1] || {});
    
    var root = {
      id: null,
      parent: null,
      children: [],
      container: element,
      position: 0
    }
    
    return Sortable._tree(element, options, root);
  },

  /* Construct a [i] index for a particular node */
  _constructIndex: function(node) {
    var index = '';
    do {
      if (node.id) index = '[' + node.position + ']' + index;
    } while ((node = node.parent) != null);
    return index;
  },

  sequence: function(element) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[1] || {});
    
    return $(this.findElements(element, options) || []).map( function(item) {
      return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
    });
  },

  setSequence: function(element, new_sequence) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[2] || {});
    
    var nodeMap = {};
    this.findElements(element, options).each( function(n) {
        if (n.id.match(options.format))
            nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
        n.parentNode.removeChild(n);
    });
   
    new_sequence.each(function(ident) {
      var n = nodeMap[ident];
      if (n) {
        n[1].appendChild(n[0]);
        delete nodeMap[ident];
      }
    });
  },
  
  serialize: function(element) {
    element = $(element);
    var options = Object.extend(Sortable.options(element), arguments[1] || {});
    var name = encodeURIComponent(
      (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
    
    if (options.tree) {
      return Sortable.tree(element, arguments[1]).children.map( function (item) {
        return [name + Sortable._constructIndex(item) + "[id]=" + 
                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
      }).flatten().join('&');
    } else {
      return Sortable.sequence(element, arguments[1]).map( function(item) {
        return name + "[]=" + encodeURIComponent(item);
      }).join('&');
    }
  }
}

// Returns true if child is contained within element
Element.isParent = function(child, element) {
  if (!child.parentNode || child == element) return false;
  if (child.parentNode == element) return true;
  return Element.isParent(child.parentNode, element);
}

Element.findChildren = function(element, only, recursive, tagName) {    
  if(!element.hasChildNodes()) return null;
  tagName = tagName.toUpperCase();
  if(only) only = [only].flatten();
  var elements = [];
  $A(element.childNodes).each( function(e) {
    if(e.tagName && e.tagName.toUpperCase()==tagName &&
      (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
        elements.push(e);
    if(recursive) {
      var grandchildren = Element.findChildren(e, only, recursive, tagName);
      if(grandchildren) elements.push(grandchildren);
    }
  });

  return (elements.length>0 ? elements.flatten() : []);
}

Element.offsetSize = function (element, type) {
  return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
}
// script.aculo.us controls.js v1.7.0, Fri Jan 19 19:16:36 CET 2007

// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
//           (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
// Contributors:
//  Richard Livsey
//  Rahul Bhargava
//  Rob Wills
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

// Autocompleter.Base handles all the autocompletion functionality 
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least, 
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method 
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most 
// useful when one of the tokens is \n (a newline), as it 
// allows smart autocompletion after linebreaks.

if(typeof Effect == 'undefined')
  throw("controls.js requires including script.aculo.us' effects.js library");

var Autocompleter = {}
Autocompleter.Base = function() {};
Autocompleter.Base.prototype = {
  baseInitialize: function(element, update, options) {
    this.element     = $(element); 
    this.update      = $(update);  
    this.hasFocus    = false; 
    this.changed     = false; 
    this.active      = false; 
    this.index       = 0;     
    this.entryCount  = 0;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || {};

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow || 
      function(element, update){ 
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false, 
            offsetTop: element.offsetHeight
          });
        }
        Effect.Appear(update,{duration:0.15});
      };
    this.options.onHide = this.options.onHide || 
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string') 
      this.options.tokens = new Array(this.options.tokens);

    this.observer = null;
    
    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix && 
      (navigator.appVersion.indexOf('MSIE')>0) &&
      (navigator.userAgent.indexOf('Opera')<0) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update, 
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },
  
  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
         return;
      }
     else 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = 
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex) 
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },
  
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },
  
  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;     
  }, 
  
  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ? 
          Element.addClassName(this.getEntry(i),"selected") : 
          Element.removeClassName(this.getEntry(i),"selected");
        
      if(this.hasFocus) { 
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },
  
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },
  
  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },
  
  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },
  
  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },
  
  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    
    var lastTokenPos = this.findLastToken();
    if (lastTokenPos != -1) {
      var newValue = this.element.value.substr(0, lastTokenPos + 1);
      var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value;
    } else {
      this.element.value = value;
    }
    this.element.focus();
    
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;   
    if(this.getToken().length>=this.options.minChars) {
      this.startIndicator();
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
  },

  getToken: function() {
    var tokenPos = this.findLastToken();
    if (tokenPos != -1)
      var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
    else
      var ret = this.element.value;

    return /\n/.test(ret) ? '' : ret;
  },

  findLastToken: function() {
    var lastTokenPos = -1;

    for (var i=0; i<this.options.tokens.length; i++) {
      var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
      if (thisTokenPos > lastTokenPos)
        lastTokenPos = thisTokenPos;
    }
    return lastTokenPos;
  }
}

Ajax.Autocompleter = Class.create();
Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    entry = encodeURIComponent(this.options.paramName) + '=' + 
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams) 
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }

});

// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
//                    text only at the beginning of strings in the 
//                    autocomplete array. Defaults to true, which will
//                    match text at the beginning of any *word* in the
//                    strings in the autocomplete array. If you want to
//                    search anywhere in the string, additionally set
//                    the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
//                   a partial match (unlike minChars, which defines
//                   how many characters are required to do any match
//                   at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
//                 Defaults to true.
//
// It's possible to pass in a custom function as the 'selector' 
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.

Autocompleter.Local = Class.create();
Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
  initialize: function(element, update, array, options) {
    this.baseInitialize(element, update, options);
    this.options.array = array;
  },

  getUpdatedChoices: function() {
    this.updateChoices(this.options.selector(this));
  },

  setOptions: function(options) {
    this.options = Object.extend({
      choices: 10,
      partialSearch: true,
      partialChars: 2,
      ignoreCase: true,
      fullSearch: false,
      selector: function(instance) {
        var ret       = []; // Beginning matches
        var partial   = []; // Inside matches
        var entry     = instance.getToken();
        var count     = 0;

        for (var i = 0; i < instance.options.array.length &&  
          ret.length < instance.options.choices ; i++) { 

          var elem = instance.options.array[i];
          var foundPos = instance.options.ignoreCase ? 
            elem.toLowerCase().indexOf(entry.toLowerCase()) : 
            elem.indexOf(entry);

          while (foundPos != -1) {
            if (foundPos == 0 && elem.length != entry.length) { 
              ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
                elem.substr(entry.length) + "</li>");
              break;
            } else if (entry.length >= instance.options.partialChars && 
              instance.options.partialSearch && foundPos != -1) {
              if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
                partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
                  elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
                  foundPos + entry.length) + "</li>");
                break;
              }
            }

            foundPos = instance.options.ignoreCase ? 
              elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
              elem.indexOf(entry, foundPos + 1);

          }
        }
        if (partial.length)
          ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
        return "<ul>" + ret.join('') + "</ul>";
      }
    }, options || {});
  }
});

// AJAX in-place editor
//
// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor

// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
  setTimeout(function() {
    Field.activate(field);
  }, 1);
}

Ajax.InPlaceEditor = Class.create();
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      paramName: "value",
      okButton: true,
      okText: "ok",
      cancelLink: true,
      cancelText: "cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      okText: "ok",
      rows: 1,
      onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      handleLineBreaks: true,
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
      highlightendcolor: "#FFFFFF",
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }
    
    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }
    
    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }
    
    this.element.title = this.options.clickToEditText;
    
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {
      okButton = document.createElement("input");
      okButton.type = "submit";


      okButton.value = this.options.okText;
      okButton.className = 'editor_ok_button';
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.className = 'editor_cancel';      
      this.form.appendChild(cancelLink);
    }
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  convertHTMLLineBreaks: function(string) {
    return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
  },
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
      text = this.getText();
    }

    var obj = this;
    
    if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = this.options.paramName;
      textField.value = text;
      textField.style.backgroundColor = this.options.highlightcolor;
      textField.className = 'editor_field';
      var size = this.options.size || this.options.cols || 0;
      if (size != 0) textField.size = size;
      if (this.options.submitOnBlur)
        textField.onblur = this.onSubmit.bind(this);
      this.editField = textField;
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = this.options.paramName;
      textArea.value = this.convertHTMLLineBreaks(text);
      textArea.rows = this.options.rows;
      textArea.cols = this.options.cols || 40;
      textArea.className = 'editor_field';      
      if (this.options.submitOnBlur)
        textArea.onblur = this.onSubmit.bind(this);
      this.editField = textArea;
    }
    
    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(this.editField);
  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
    Field.scrollFreeActivate(this.editField);
  },
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var form = this.form;
    var value = this.editField.value;
    
    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();
    
    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true, 
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null }, 
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};

Ajax.InPlaceCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceCollectionEditor.prototype, {
  createEditField: function() {
    if (!this.cached_selectTag) {
      var selectTag = document.createElement("select");
      var collection = this.options.collection || [];
      var optionTag;
      collection.each(function(e,i) {
        optionTag = document.createElement("option");
        optionTag.value = (e instanceof Array) ? e[0] : e;
        if((typeof this.options.value == 'undefined') && 
          ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
        if(this.options.value==optionTag.value) optionTag.selected = true;
        optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
        selectTag.appendChild(optionTag);
      }.bind(this));
      this.cached_selectTag = selectTag;
    }

    this.editField = this.cached_selectTag;
    if(this.options.loadTextURL) this.loadExternalText();
    this.form.appendChild(this.editField);
    this.options.callback = function(form, value) {
      return "value=" + encodeURIComponent(value);
    }
  }
});

// Delayed observer, like Form.Element.Observer, 
// but waits for delay after last key input
// Ideal for live-search fields

Form.Element.DelayedObserver = Class.create();
Form.Element.DelayedObserver.prototype = {
  initialize: function(element, delay, callback) {
    this.delay     = delay || 0.5;
    this.element   = $(element);
    this.callback  = callback;
    this.timer     = null;
    this.lastValue = $F(this.element); 
    Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  },
  delayedListener: function(event) {
    if(this.lastValue == $F(this.element)) return;
    if(this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
    this.lastValue = $F(this.element);
  },
  onTimerEvent: function() {
    this.timer = null;
    this.callback(this.element, $F(this.element));
  }
};
// script.aculo.us slider.js v1.7.0, Fri Jan 19 19:16:36 CET 2007

// Copyright (c) 2005, 2006 Marty Haught, Thomas Fuchs 
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

if(!Control) var Control = {};
Control.Slider = Class.create();

// options:
//  axis: 'vertical', or 'horizontal' (default)
//
// callbacks:
//  onChange(value)
//  onSlide(value)
Control.Slider.prototype = {
  initialize: function(handle, track, options) {
    var slider = this;
    
    if(handle instanceof Array) {
      this.handles = handle.collect( function(e) { return $(e) });
    } else {
      this.handles = [$(handle)];
    }
    
    this.track   = $(track);
    this.options = options || {};

    this.axis      = this.options.axis || 'horizontal';
    this.increment = this.options.increment || 1;
    this.step      = parseInt(this.options.step || '1');
    this.range     = this.options.range || $R(0,1);
    
    this.value     = 0; // assure backwards compat
    this.values    = this.handles.map( function() { return 0 });
    this.spans     = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false;
    this.options.startSpan = $(this.options.startSpan || null);
    this.options.endSpan   = $(this.options.endSpan || null);

    this.restricted = this.options.restricted || false;

    this.maximum   = this.options.maximum || this.range.end;
    this.minimum   = this.options.minimum || this.range.start;

    // Will be used to align the handle onto the track, if necessary
    this.alignX = parseInt(this.options.alignX || '0');
    this.alignY = parseInt(this.options.alignY || '0');
    
    this.trackLength = this.maximumOffset() - this.minimumOffset();

    this.handleLength = this.isVertical() ? 
      (this.handles[0].offsetHeight != 0 ? 
        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : 
      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : 
        this.handles[0].style.width.replace(/px$/,""));

    this.active   = false;
    this.dragging = false;
    this.disabled = false;

    if(this.options.disabled) this.setDisabled();

    // Allowed values array
    this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false;
    if(this.allowedValues) {
      this.minimum = this.allowedValues.min();
      this.maximum = this.allowedValues.max();
    }

    this.eventMouseDown = this.startDrag.bindAsEventListener(this);
    this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
    this.eventMouseMove = this.update.bindAsEventListener(this);

    // Initialize handles in reverse (make sure first handle is active)
    this.handles.each( function(h,i) {
      i = slider.handles.length-1-i;
      slider.setValue(parseFloat(
        (slider.options.sliderValue instanceof Array ? 
          slider.options.sliderValue[i] : slider.options.sliderValue) || 
         slider.range.start), i);
      Element.makePositioned(h); // fix IE
      Event.observe(h, "mousedown", slider.eventMouseDown);
    });
    
    Event.observe(this.track, "mousedown", this.eventMouseDown);
    Event.observe(document, "mouseup", this.eventMouseUp);
    Event.observe(document, "mousemove", this.eventMouseMove);
    
    this.initialized = true;
  },
  dispose: function() {
    var slider = this;    
    Event.stopObserving(this.track, "mousedown", this.eventMouseDown);
    Event.stopObserving(document, "mouseup", this.eventMouseUp);
    Event.stopObserving(document, "mousemove", this.eventMouseMove);
    this.handles.each( function(h) {
      Event.stopObserving(h, "mousedown", slider.eventMouseDown);
    });
  },
  setDisabled: function(){
    this.disabled = true;
  },
  setEnabled: function(){
    this.disabled = false;
  },  
  getNearestValue: function(value){
    if(this.allowedValues){
      if(value >= this.allowedValues.max()) return(this.allowedValues.max());
      if(value <= this.allowedValues.min()) return(this.allowedValues.min());
      
      var offset = Math.abs(this.allowedValues[0] - value);
      var newValue = this.allowedValues[0];
      this.allowedValues.each( function(v) {
        var currentOffset = Math.abs(v - value);
        if(currentOffset <= offset){
          newValue = v;
          offset = currentOffset;
        } 
      });
      return newValue;
    }
    if(value > this.range.end) return this.range.end;
    if(value < this.range.start) return this.range.start;
    return value;
  },
  setValue: function(sliderValue, handleIdx){
    if(!this.active) {
      this.activeHandleIdx = handleIdx || 0;
      this.activeHandle    = this.handles[this.activeHandleIdx];
      this.updateStyles();
    }
    handleIdx = handleIdx || this.activeHandleIdx || 0;
    if(this.initialized && this.restricted) {
      if((handleIdx>0) && (sliderValue<this.values[handleIdx-1]))
        sliderValue = this.values[handleIdx-1];
      if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1]))
        sliderValue = this.values[handleIdx+1];
    }
    sliderValue = this.getNearestValue(sliderValue);
    this.values[handleIdx] = sliderValue;
    this.value = this.values[0]; // assure backwards compat
    
    this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = 
      this.translateToPx(sliderValue);
    
    this.drawSpans();
    if(!this.dragging || !this.event) this.updateFinished();
  },
  setValueBy: function(delta, handleIdx) {
    this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, 
      handleIdx || this.activeHandleIdx || 0);
  },
  translateToPx: function(value) {
    return Math.round(
      ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * 
      (value - this.range.start)) + "px";
  },
  translateToValue: function(offset) {
    return ((offset/(this.trackLength-this.handleLength) * 
      (this.range.end-this.range.start)) + this.range.start);
  },
  getRange: function(range) {
    var v = this.values.sortBy(Prototype.K); 
    range = range || 0;
    return $R(v[range],v[range+1]);
  },
  minimumOffset: function(){
    return(this.isVertical() ? this.alignY : this.alignX);
  },
  maximumOffset: function(){
    return(this.isVertical() ? 
      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
        this.track.style.height.replace(/px$/,"")) - this.alignY : 
      (this.track.offsetWidth != 0 ? this.track.offsetWidth : 
        this.track.style.width.replace(/px$/,"")) - this.alignY);
  },  
  isVertical:  function(){
    return (this.axis == 'vertical');
  },
  drawSpans: function() {
    var slider = this;
    if(this.spans)
      $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) });
    if(this.options.startSpan)
      this.setSpan(this.options.startSpan,
        $R(0, this.values.length>1 ? this.getRange(0).min() : this.value ));
    if(this.options.endSpan)
      this.setSpan(this.options.endSpan, 
        $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum));
  },
  setSpan: function(span, range) {
    if(this.isVertical()) {
      span.style.top = this.translateToPx(range.start);
      span.style.height = this.translateToPx(range.end - range.start + this.range.start);
    } else {
      span.style.left = this.translateToPx(range.start);
      span.style.width = this.translateToPx(range.end - range.start + this.range.start);
    }
  },
  updateStyles: function() {
    this.handles.each( function(h){ Element.removeClassName(h, 'selected') });
    Element.addClassName(this.activeHandle, 'selected');
  },
  startDrag: function(event) {
    if(Event.isLeftClick(event)) {
      if(!this.disabled){
        this.active = true;
        
        var handle = Event.element(event);
        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
        var track = handle;
        if(track==this.track) {
          var offsets  = Position.cumulativeOffset(this.track); 
          this.event = event;
          this.setValue(this.translateToValue( 
           (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2)
          ));
          var offsets  = Position.cumulativeOffset(this.activeHandle);
          this.offsetX = (pointer[0] - offsets[0]);
          this.offsetY = (pointer[1] - offsets[1]);
        } else {
          // find the handle (prevents issues with Safari)
          while((this.handles.indexOf(handle) == -1) && handle.parentNode) 
            handle = handle.parentNode;
            
          if(this.handles.indexOf(handle)!=-1) {
            this.activeHandle    = handle;
            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
            this.updateStyles();
            
            var offsets  = Position.cumulativeOffset(this.activeHandle);
            this.offsetX = (pointer[0] - offsets[0]);
            this.offsetY = (pointer[1] - offsets[1]);
          }
        }
      }
      Event.stop(event);
    }
  },
  update: function(event) {
   if(this.active) {
      if(!this.dragging) this.dragging = true;
      this.draw(event);
      // fix AppleWebKit rendering
      if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
      Event.stop(event);
   }
  },
  draw: function(event) {
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    var offsets = Position.cumulativeOffset(this.track);
    pointer[0] -= this.offsetX + offsets[0];
    pointer[1] -= this.offsetY + offsets[1];
    this.event = event;
    this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] ));
    if(this.initialized && this.options.onSlide)
      this.options.onSlide(this.values.length>1 ? this.values : this.value, this);
  },
  endDrag: function(event) {
    if(this.active && this.dragging) {
      this.finishDrag(event, true);
      Event.stop(event);
    }
    this.active = false;
    this.dragging = false;
  },  
  finishDrag: function(event, success) {
    this.active = false;
    this.dragging = false;
    this.updateFinished();
  },
  updateFinished: function() {
    if(this.initialized && this.options.onChange) 
      this.options.onChange(this.values.length>1 ? this.values : this.value, this);
    this.event = null;
  }
}
var gradientshadow={}
gradientshadow.depth=6 //Depth of shadow in pixels
gradientshadow.containers=[]

gradientshadow.create=function(){
var a = document.all ? document.all : document.getElementsByTagName('*')
for (var i = 0;i < a.length;i++) {
	if (a[i].className == "shadow") {
		var newSdBox = document.createElement("DIV")	
		newSdBox.id="sbox_"+a[i].id;
		a[i].parentNode.appendChild(newSdBox);
		for (var x=0; x<gradientshadow.depth; x++){
			var newSd = document.createElement("DIV")
			newSd.className = "shadow_inner"
			newSd.id="shadow"+gradientshadow.containers.length+"_"+x //Each shadow DIV has an id of "shadowL_X" (L=index of target element, X=index of shadow (depth) 
			if (a[i].getAttribute("rel"))
				newSd.style.background = a[i].getAttribute("rel")
			else
				newSd.style.background = "black" //default shadow color if none specified
			document.getElementById(newSdBox.id).appendChild(newSd);
		}
	gradientshadow.containers[gradientshadow.containers.length]=a[i];
	}
}
gradientshadow.position()
//window.onresize=function(){
//	gradientshadow.position()
//}
}


gradientshadow.position=function(){

if ((gradientshadow.containers.length>0) && (navigator.userAgent.indexOf( 'Safari' ) == -1 )){
try{
	for (var i=0; i<gradientshadow.containers.length; i++){
		for (var x=0; x<gradientshadow.depth; x++){
  		var shadowdiv=document.getElementById("shadow"+i+"_"+x)
  		//	var xy= Position.page(gradientshadow.containers[i]);
			shadowdiv.style.width = (gradientshadow.containers[i].offsetWidth-(6 +x)) + "px"
			shadowdiv.style.height = gradientshadow.containers[i].offsetHeight  + "px"
			//shadowdiv.style.left = gradientshadow.containers[i].offsetLeft - x + "px"
		//	shadowdiv.style.left = xy[0] + "px"
		//	shadowdiv.style.top = xy[1] + x + "px"
			shadowdiv.style.left =   "0px"



			shadowdiv.style.top =  x + "px"
		}
	}
	}
	catch (err){}
	

}
}
// JavaScript Document

function startUp()
{
  	try{
  		pageLoader();
  	}
  	catch(err) {
  	}
}
function setClass(divName, cls)
{
	var div = $(divName);
	div.className = cls;
}
/** functions rollOut and rollIn
  Shared by pages that use the sliders (scene_ad,scene_editorial,designing_studio)
  **/
function rollOut()
{
	if (isOpen)
		{
			rollIn(null);
			return;
		}
		else
		{
		$('shellQV').style.width="";
		isOpen= true;
		setClass('div_btns', "activeRight");
		toggleFold('div_container', .1, .6);
	}
}
function rollIn(img, currentImage)
{
	$('shellQV').style.width="auto";
	isOpen= false;
	hideDiv('div_container', .01, .3);
	objImages.setLargeImage(currentImage);
	if (BrowserDetect.browser == "Netscape" && BrowserDetect.version < 7.2){
		$('mainQV').show(); // Netscape can't handle effects
	} else {
		$('mainQV').hide();
		new Effect.Appear('mainQV', {duration: .7 });
	}
	setClass('div_btns', "inactiveLeft");
}

// SPECIAL FUNCITONS
/* viewport() FROM JQUERY TOOLTIP
/*
 * Tooltip 1.0 - jQuery plugin  for styled tooltips
 *
 * Copyright (c) 2006 Jörn Zaefferer, Stefan Petre
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */
function viewport() {
		var e = document.documentElement || {},
			b = document.body || {},
			w = window;
		function min() {
			var v = Infinity;
			for( var i = 0;  i < arguments.length;  i++ ) {
				var n = arguments[i];
				if( n && n < v ) v = n;
			}
			return v;
		}
		return {
			x: w.pageXOffset || e.scrollLeft || b.scrollLeft || 0,
			y: w.pageYOffset || e.scrollTop || b.scrollTop || 0,
			cx: min( e.clientWidth, b.clientWidth, w.innerWidth ),
			cy: min( e.clientHeight, b.clientHeight, w.innerHeight )
		};
	}
/** function positionElements1
DEPENDS ON GLOBAL VARS mXPos and mYPos. - normally tied to mouse position like so
	var mXPos;
	var mYPos;
	Event.observe(document, "mousedown", setMousePos, false);
	function setMousePos(event){
		mXPos = Event.pointerX(event);
		mYPos = Event.pointerY(event);
	}

 - or - 
 
SET DESIRED POSITION BEFORE CALLING FUNCTION.
	// example
	var mXPos=100;
	var mYPos=200;

PARMS:	
	popDivID - [string] id of absolute div to place
	xOffset - [int] move top left corner right by this many pixels (negative ok).
	yOffset - [int move top left corner down by this many pixels (negative ok).
	keepOnPage - [true/false] checks page to make sure popup will fit, if not, move so it does.
	forceWidth - [int] makes this function assume the width of the popup to be the value of this parameter.
				 used for repositioning purposes when keepOnPage is true.
				 Recommend using this if content is dynamically populated.
**/
function positionElements1(popDivID,xOffset,yOffset,keepOnPage,forceWidth, forceHeight)
{
	try{
		// uses viewport() from jquery tooltip.
		var v = viewport();
	
		var divProductContent = $(popDivID);
		

		if (divProductContent != null){
	
			if (arguments.length<6)
				forceHeight = 350;
	
			if(forceWidth>0){
				divWidth=forceWidth;
			} else {
				divWidth=$(popDivID).getWidth();
			}
			
			if(forceHeight>0){
				divHeight=forceHeight;
			} else {
				divHeight=$(popDivID).getHeight();
			}
	
			
			if (keepOnPage){
				//if the mouse position plus is too close to the right side of the page, put the popup on the right edge of the page			
				rightEdge=mXPos-xOffset+divWidth;
				pageEdge=v.x + v.cx;
				if(pageEdge< rightEdge) {
				//increase offset
				xOffset=xOffset+(rightEdge-pageEdge)-10;
				}
				//if the mouse position plus is too close to the left side of the page, put the popup on the left edge of the page			
				leftEdge=mXPos-xOffset;
				if(leftEdge<0) {
				//increase offset
				xOffset=0;
				mXPos=10;
				}
	
				/*alina's update - to make sure that it fits over the fold */
				bottomEdge=mYPos-yOffset+divHeight;

				pageBottom=v.y + v.cy;
				if(pageBottom< bottomEdge)
					yOffset=yOffset+(bottomEdge-pageBottom)-10;
				bottomEdge=mYPos-yOffset;
				if(bottomEdge<0) {
					yOffset=0;
					mYPos=10;
				}
			}
			divProductContent.style.left=mXPos-xOffset+"px";
			divProductContent.style.top=mYPos-yOffset+"px";
		}		
	}
	catch (err)
	{}
}

function toggleFold (div_id, shadowInterval, divInterval)
{
if (($(div_id).offsetWidth== 0)|| ($(div_id).offsetWidth== null))
showDiv(div_id, shadowInterval, divInterval);
}

function btnsBg(state)
{
	var active;
	var direction;
	
	if (isOpen)
		direction = "Right";
	else
		direction = "Left";
	
	if (state=="off" && !isOpen)
	  active = "inactive";
	else
		active = "active";
	//buggit(active+ direction);
	setClass('div_btns', active+direction);
}

function doPage(type, page)
{alert ("to implement");
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


/** function lockAndLoad
 	sets lock state and puts loading msg in div
 	PARMS: 
 		id [id of div]= div to update
 		msg [html]= content of div
 **/
function lockAndLoad(id,msg){
	lock=true;
	$(id).innerHTML = msg;
}
function unlock(){
	lock=false;
}
function lockBtns(){
	lock=true;
}

function hideDiv(div, shadowInterval, divInterval)
{     // shadowInterval is depreciated... no use - jmdill 7/15
      if (BrowserDetect.browser == "Netscape" && BrowserDetect.version < 9){
            hideFast(div); //Netscape unable to handle Effect
            return;
      }
      clearQueue('myQueue');
      $('sbox_div_container').hide(); // Effects don't work on shadows...just hide and show.  - jmdill 7/15
      //new Effect.SwitchOff('sbox_div_container', { duration: shadowInterval, queue: { position: "end", scope: "myQueue" }});
      new Effect.BlindLeft(div, { duration: divInterval, queue: { position: "end", scope: "myQueue" },beforeStart:lockBtns,afterFinish:function(){unlock();reallyHideDiv(div);} });
}
//hack for firefox – basically sets the parent slider object to a width of 25 (the width of the buttons)
function reallyHideDiv(div) {
      divObj = document.getElementById(div);
divObj.parentNode.style.width = '25px';
}
function showDiv(div, shadowInterval, divInterval)
{
      if (BrowserDetect.browser == "Netscape" && BrowserDetect.version < 9){
            showFast(div);//Netscape unable to handle Effect
            return;
      }
      clearQueue('myQueue');
      divObj = document.getElementById(div);
      divObj.parentNode.style.width = '';
      new Effect.BlindRight(div, {duration: divInterval, queue: { position: "end", scope: "myQueue" },beforeStart:lockBtns, afterFinish:function(){unlock();$('sbox_div_container').show();} });
      //new Effect.Appear('sbox_div_container', {duration: shadowInterval, queue: { position: "end", scope: "myQueue" } });
}

function hideFast(div)
{
	$(div).hide();
	$('sbox_div_container').hide();
}
function showFast(div)
{
	$(div).show();
	$('sbox_div_container').show();
}



function myCallBackOnFinish(obj){}
function myCallBackOnStart(obj){}
function clearQueue(queue){
	var queue = Effect.Queues.get(queue);
	queue.each(function(e) { e.cancel() });
}

/* AJAX BASED FUNCTIONS */
function updateCartCount(url)
{
	var randomnumber=Math.floor(Math.random()*100001);
	url+="&rnd="+randomnumber+"&decoparam=blank.jsp";
	var result ='';
    var request = new Ajax.Updater('cartCount',url, 
    { 
      method:'get',
      onSuccess: function(transport)
      { 
  	  // do nothing for now.  update of cartCount is complete
      },
      onFailure: function()
      {
      //ALERT FOR DEBUGGING ONLY.  REMOVE ALERTS IN PRODUCTION.
     // 	alert('failure:'+url);
    }
    }
  );
 };
function updateClosetCount(url)
{
	var randomnumber=Math.floor(Math.random()*100001);
	url+="&rnd="+randomnumber+"&decoparam=blank.jsp";
	var result ='';
    var request = new Ajax.Updater('closetCount',url, 
    { 
      method:'get',
      onSuccess: function(transport)
      { 
      //alert(request.transport.responseText);
  	  // do nothing for now.  update of closetCount is complete
      },
      onFailure: function()
      {
      //ALERT FOR DEBUGGING ONLY.  REMOVE ALERTS IN PRODUCTION.
    //  	alert('failure:'+url);
      }
    }
  );
 };

if (window.addEventListener)
{
	window.addEventListener("load", gradientshadow.create, false)
	window.addEventListener("load", startUp, false)
} else if (window.attachEvent){
	window.attachEvent("onload", gradientshadow.create)
	window.attachEvent("onload", startUp)
} else if (document.getElementById){
	window.onload=gradientshadow.create
	window.onload=startUp
 }
var objImages = {
"currentPage" : 0,
"currentImage":0,
"totalPages":0,
"pageSize":0,
"imageForder": "",
"images" :[] ,
		   
	init : function(arrayAsJSONText, imgFolder, pageSize, noThumbs ) {
		this.images=eval(arrayAsJSONText) ;	
		this.imageFolder = imgFolder;
		this.pageSize= pageSize;
		this.totalPages = Math.floor(this.images.length /this.pageSize)+1;
		this.currentPage=0;
		this.currentImage=0;
		var startNdx= this.currentPage * this.pageSize;	
		if (!noThumbs) this.displayImages (startNdx);
	/*
		if  ((arguments.length) == 4){
			
			for (i = 0; i < this.images.length; i ++){
				
				if (this.images[i].id == arguments[3]){
					this.currentImage=i;
					break;
				}
			}
		}
		else
		{
		// NEW IMPLEMENTATION REQUIRES THAT BG FOR SHELLQV IS TRANSPARENT.  IMAGES ARE ALWAYS LOADED IN div_img NOW.
		$('shellQV').style.background="url('"+this.imageFolder + this.images[this.currentImage].large+"') ";
		$('shellQV').style.backgroundRepeat='no-repeat'; 
	
		}
	*/
		
	},
		   
	displayImages: function(startNdx){
		var str= "";
		var div = window.document.getElementById('div_thumbImages');
		var endNdx = startNdx + this.pageSize;			
		if (endNdx >= this.images.length)
			endNdx = this.images.length;
		for (i = startNdx; i < endNdx; i ++){
			str= str +" <img src=\""+ this.imageFolder + this.images[i].small+ "\" onclick=\"javascript:rollIn('"+this.imageFolder + this.images[i].large+ "\', " + i + ")\" />";
		}
		div.innerHTML=str; 
	},
		   
		  
	setLargeImage:function(imageId){
		if (imageId != null)
		this.currentImage= imageId;
		img = this.images[this.currentImage];
		$('div_img').src=this.imageFolder + img.large;	
		if (img.maps != null && img.maps.length >0 && $('map') != null){
			$('div_img').useMap="#map"+imageId;
			var outputString= "<map name=\"map"+imageId+"\">";
		  	for (i = 0; i < img.maps.length; i ++){
		  		if (img.maps[i].coords !=""){
					outputString += "<area shape=\"" + img.maps[i].shape + "\"";
	        		outputString += " coords=\"" + img.maps[i].coords + "\"";
	        		switch (img.maps[i].sellStatus)
	        		{
	        		case "available":	        		
						outputString += " onmouseover=\"ddrivetip(tipImg+'Click for Detail');\"";
	        			outputString += " href=\"javascript:getProductContent('"+img.maps[i].prodId+"')\"";
	        		break;
	        		case "notAvailable":
	        		case "soldOut":
						outputString += " onmouseover=\"ddrivetip('So Hot, It\\&#39;s Sold Out',null,110);\"";
	        			outputString += " href=\"#\"";	        			
	        			outputString += " onclick=\"return false;\"";
	        		break;
	        		case "comingSoon":
						outputString += " onmouseover=\"ddrivetip('Coming Soon','white',70);\"";
	        			outputString += " href=\"#\"";	        			
	        			outputString += " onclick=\"return false;\"";
	 				break;
	 				}//close switch
	 				outputString += " onmouseout=\"hideddrivetip();\" />";;
        		}
			}
			outputString += "</map>";
			$('map').update(outputString);
		}
		try{
			reportLookView(img.id);
		} catch (err){}
	},
		   
	getCurrentProducts: function(){
		return this.images[this.currentImage].products;
	},
	
	getCurrentImage :function (){
		return this.imageFolder + this.images[this.currentImage].large;
	},
		   
	navigateImage: function (theImage){
		var newCurrentImage = this.currentImage + eval(theImage);
		if (newCurrentImage < 0)
		   	newCurrentImage = this.images.length-1;
		if (newCurrentImage >= this.images.length)
		   	newCurrentImage= 0;
		this.setLargeImage(newCurrentImage, true);
	},
		   
	page: function(thePage){
		this.currentPage = this.currentPage + eval(thePage)
		if (this.currentPage < 0)
		   this.currentPage = this.totalPages-1;
		if (this.currentPage >= this.totalPages)
		   this.currentPage= 0;
		var startNdx = this.currentPage * this.pageSize;
		this.displayImages(startNdx);
	},
		   
	show :function (x){
		$('status').update(x);
	}
}
// JavaScript Document
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function reportLookView(lookNumber)
{
	s.pageName="Static: "+lookNumber;
	s.server="";
	s.channel="";
	s.pageType="";
	s.prop1="LookBook Look Viewed";
	s.prop2="";
	s.prop3="";
	s.prop4="";
	s.prop5="";
	/* Conversion Variables */
	s.campaign="";
	s.state="";
	s.zip="";
	s.events="";
	s.event="";
	s.products="";
	s.purchaseID="";
	s.eVar1="";
	s.eVar2="";
	s.eVar3="";
	s.eVar4="";
	s.eVar5="";
	void(s.t());
}
-->
