// ***************************************************************
//  cufon Replacements
// ****************************************************************


Cufon.replace('h3,  .block_welcome p, #filterpanel p.prompt', {fontFamily: 'ArrowLight'});
Cufon.replace('.block_text p, .block_text li, .teaser, .block_ads, #contact,  #searchform h1, #searchform h2, #searchform p, #searchform #submit_box input, th', {fontFamily: 'ArrowMedium'});
   

// ***************************************************************
//  domReady handler
// ****************************************************************



window.addEvent ('domready', function(){


//SET PRE PAGE-BUILD ANIMATION STATES

	//Set the main image transparent if it exists	
	if (document.getElement('.block_image')) {document.getElement('.block_image').setStyle('opacity','0'); }
	
	//Hide Secondary Nav if it exists
	if ($('secondary')) { $('secondary').setStyle('opacity','0'); };

	
	
//Setup the Utility Pages Sidenav 

	if (document.getElement('#nav_tertiary.utility')) {
	
		var sides = document.getElements('.utility ul.filterform li a');
		
		sides.each (function(el){				
						
			el.addEvent('click', function(e) {
									
				//change the class of the wrapper 'plate' to the new
				//page derived by splitting the 'nav_' off of the
				//id of the sidenav navigation li
				
				var page = el.getProperty('href').split("#")[1];
				$('plate').removeProperty('class');
				$('plate').addClass(page);
			
				//reinitialize the pages based on the new section.
				initPages();
				e.preventDefault();

			});
		

		});
	
		
		} //if sidenav
	



//Setup Secondary nav if any

/*
	if ($('secondary')) {	
		var width = $('secondary').getSize().x.toInt();
		var items = $$('#secondary ul.nav li');
		distributeItems (width, items);
	}
*/

//Setup Tertiary nav if any

	if ($('nav_tertiary')) {
		var width = $('nav_tertiary').getSize().x.toInt();
		var items = $$('#nav_tertiary ul.filterform li');
		distributeItems (width, items);
	
	}



//Diamond Search 
	// A. select all and deselect all
	if ($('diamondform')) {
	
		var categories = document.getElements('fieldset');

		categories.each (function(el){	
		var triggers = el.getElements('.box-flex a');			
		var inputs = el.getElements('input');	
			triggers.each(function(inp){
					inp.addEvent('click', function(event){
					event.preventDefault();
					if (inp.hasClass('selectall')){
						checkAllCheckboxes(inputs);
					} else {
						UncheckAllCheckboxes(inputs);				
					}					
					});
			
			});
		});		
		}	

	// B. assign a class to every other row in the search results (for bg image aesthetic purposes):
	var rows = $$('tr:even');
		rows.each(function(row){
			row.addClass('even');
		});
		

	// C. "request to see this diamond" form
	var type = document.getElements('fieldset.personal-info input, fieldset.personal-info textarea, #carat_box input, #price_box input');
	
	type.each(function(typ){
		
		var original = typ.getProperty("value");
		
		// highlight the field and remove default text
		typ.addEvent('focus', function(){
		typ.addClass('highlight');
		if (typ.getProperty("value")==original){
				typ.setProperty('value', "");
				} 
		});
		
		// unhighlight the field and put back in default text if nothing is entered
		typ.addEvent('blur', function(){	
		typ.removeClass('highlight');
			if (typ.getProperty("value")==""){
				typ.setProperty('value', original);
				} 
		});
	
	});
	
	$('minprice').addEvent("change",function() { $('anyprice').removeProperty("checked") });
	$('maxprice').addEvent("change",function() { $('anyprice').removeProperty("checked") });
	$('mincarat').addEvent("change",function() { $('anycarat').removeProperty("checked") });
	$('maxcarat').addEvent("change",function() { $('anycarat').removeProperty("checked") });
	$('dsearch_reset').addEvent("click",function() {
		$('diamondform').getElements('input[type=checkbox]').removeProperty("checked");
		$('anycarat').setProperty("checked","checked");
		$('anyprice').setProperty("checked","checked");
		return false;
	});
	



}); // end domReady handler










// ****************************************************************
// onload handler
// ****************************************************************


window.addEvent ('load', function(){


	//fade in the homepage curtain
	if ($('curtain')) {
		$('curtain').fade('out');	
		$('curtain').dispose();
	}


	milkbox = new Milkbox({topPosition:'50%'});



/*
	var reveal = $$('.conceal');
	reveal.each (function(el){
		el.fade('in');
		el.removeClass('conceal');
	});
*/

	var loadings = $$('.loading');
	loadings.each (function(el){
		el.removeClass('loading');
	});



	
//************ HOME PAGE BEHAVIORS *****************

if ($('wrapper').get('class') == 'home') {

	if (document.getElement('.newsevents')) {
		var newsItems = $$('.newsevents');
		if (newsItems.length > 1) {
			newsItems.each (function(element){
				element.setStyles({'opacity':0})		
				var content = element.getFirst('p');
				content.setStyle('top',vCenter('.newsevents', content));	
			});
			fadeLoop(newsItems, 6000, 'popfade', 'newsloop');
		} else {
			var content = document.getElement('.newsevents').getFirst('p');
			content.setStyle('top',vCenter('.newsevents', content));				
		}
	}
	
	if(document.getElement('.promo')) {
		var promoItems = $$('.promo');
		if (promoItems.length > 1) {
		promoItems.each (function(el){
			el.setStyles({'opacity':0})		
			var content = el.getFirst('p');
			content.setStyle('top',vCenter('.promo',content));	
		});
		fadeLoop(promoItems, 12000, 'crossfade', 'promoloop');
		} else {
			var content = document.getElement('.promo').getFirst('p');
			content.setStyle('top',vCenter('.promo', content));				
		}
	
	}

} // end home page behaviors




	//Set the main image transparent and instantiate
	//an FX object for later use.
	//Sometime when viewing cached pages in Safari, the load handler will
	//fire *before* the domReady handler, so reset the main image transparency
	//and instantiate the FX object here just in case

	if (document.getElement('.block_image')) 
	
	{	
		mainImage = document.getElement('.block_image');
		imageFx = new Fx.Tween(mainImage, {duration:750, link:'ignore'});
	}
	
	
	//Initialize Page elements	
	initPages();	
	initScroll();	
	initScanner();	



	//Instantiate FX objects
	navFx = new Fx.Tween($('secondary'), {duration:800, transition:Fx.Transitions.Cubic.easeOut, link:'chain'});	
	
	//Fade in the main image
	if(document.getElement('.block_image')) { imageFx.start('opacity','1'); }	
	
	//If there's a scanner, start it and then fade in secondary nav
	//If no scanner, just fade in secondary nav
	if(document.getElement('.block_scanner')) {	
		scannerFx.start('left',scannerEndPos).chain(function(){ showSecondaryNav(); });	
	} else {
		showSecondaryNav();	
	}
	





//************* MAIN JEWELRY LISTING INTERFACE *****************	
	
//Setup the product listings clicks, scroll, and image display

																														/* !products */

	if (document.getElement('ul.itemlist')) {
	

		var imagePath = "_images/products/";	
		var liWidth = 0;
		imageTag = 'displayarea';
		itemsUl = document.getElement('ul.itemlist')
		viewPort = $('viewport');
		scrollInterval = viewPort.getSize().x/10; scrollInterval = scrollInterval - 3.5;	
				
		
		//Instantiate the main slide animation object and callback function
		itemsSlide = new Fx.Tween(itemsUl, 
		
										{	duration:1000, 
											unit:'em', 
											transition:Fx.Transitions.Quart.easeInOut,
											onComplete: function() { updatePageStatus(scrollInterval); }
										}
									);
											



	/****** Initial View Item Display*******/
	
	//Display either landing page info or 
	//the first product and description when page
	//depending on whether or not there is landing page info
	//and if you've clicked on an item 



	if (!$('wrapper').hasClass('selector')) { //Don't do any of this for the designer selector page 

		if (window.location.hash != "") {
			//entered page with a product anchor so grab
			//the anchor -- the sku-- and display
			var sku = window.location.hash.substring(1);
			$('plate').addClass('itempage');
			$('plate').removeClass('landingpage');
			var itemID = "#sku_"+sku+" div.details";
			var desc = document.getElement(itemID).get('html');
			displayMainImage(imagePath, imageTag, sku, desc);
			
		} else {
		
			//entered page without an anchor hash so 
			//check to see if there is landing page information
			//and setup page elements as a landing page.  If it is not a landing
			//page just grab the first item in the itemlist and display
			
			if ($('plate').hasClass('landingpage')) {
				//add the landingpage description click event
				var descFx = new Fx.Morph($('description'), {transition:Fx.Transitions.Quart.easeOut, link:'cancel', duration:'600'});
				$('description').addEvent('click', function(){
					this.set('morph', {transition:Fx.Transitions.Quart.easeOut, link:'cancel', duration:'600'} );
					if (this.hasClass('expanded')){ 
						descFx.start('.hide');
						this.getFirst('img.logo').morph({'margin-top':0});
						this.addClass('hide');
						this.removeClass('reveal');
						
					} else {
						var boxHeight = this.getSize().y.toInt();
						var textHeight = this.getFirst('p.desc').getCoordinates().height.toInt();
						var logoHeight = this.getFirst('img.logo').getCoordinates().height.toInt();
						var centerText = ((boxHeight/2)-(textHeight/1.2))-logoHeight;
						descFx.start('.reveal');
						this.getFirst('img.logo').set('morph', {transition:Fx.Transitions.Quart.easeOut, link:'cancel', duration:'600'} );
						this.getFirst('img.logo').morph({'margin-top':centerText});
						this.removeClass('hide');
						this.addClass('reveal');

					}

					this.toggleClass('expanded');			
				});
			
			} else {
				//Grab the sku from the first item and display
					if (document.getElement('.itemlist li.imagelinks')) {
					var sku = document.getElement('.itemlist li.imagelinks').getProperty('id').split("_")[1]; 
					var itemID = "#sku_"+sku+" div.details";
					//alert (itemID);
					var desc = document.getElement(itemID).get('html');
					displayMainImage(imagePath, imageTag, sku, desc);
				}
			}
		}
		
	} //close the check for the designer selector page
	
	
	
		//setup the onclick events for each product thumbnail
		//and calculate total width of all thumbnails
		
		var items = document.getElements('ul.itemlist li.imagelinks');
		items.each (function(el){				
			
			//calculate the total width of all li elements
			//in order to properly size the enlcosing ul
			//to ensure two rows of list items			
			itemWidth = el.getSize().x.toInt()+el.getStyle('margin-right').toInt();
			liWidth = liWidth + (itemWidth);
	
			if (!$('wrapper').hasClass('selector')) { 
			//exclude this click avent for the designer selector page 
			//since that page does not have any image to display
			
				el.addEvent('mouseenter', function() {
					el.addClass('producthover');					
				});

				el.addEvent('mouseleave', function() {
					el.removeClass('producthover');
				});
		
						
				el.addEvent('click', function() {
					if (document.getElement('.productselected')) {
						document.getElement('.productselected').removeClass('productselected');				
					}
					el.addClass('productselected');						
					//grab the sku from the achored URL	
					var sku	 = el.getFirst('a').getProperty('href').split("#")[1];
					var desc = el.getFirst('div').get('html');
					mainImage.setStyle('opacity',0);
					
					//if previous page was a landing page, remove that class
					//so product image will be displayed at normal (non-landing page size)
					//also remove click event and styling to the description text added for
					//landing page specific styling and behavior
					$('plate').removeClass('landingpage');
					$('plate').addClass('itempage');
					$('description').removeClass('expanded');
					$('description').removeClass('hide');
					$('description').removeClass('reveal');
					$('description').removeProperty('style');
					$('description').removeEvents('click');
					$('description').setStyle('opacity',0);
					displayMainImage(imagePath, imageTag, sku, desc);
					
				
				});
		
		} //close the check for the designer selector page		
		
		}); //end items.each loop
	
	
				
		//calculate width of the ul based on the number and width of list items
		//Since items are on two rows we divide the total number of items
		//by 2 and then round up. Then we multiply by the width of the item
		var listWidth = (((items.length/2)+.5).toInt())*itemWidth;
		listWidth = (listWidth/10); //convert to ems

		
		/**** Setup Page Counter List Controller ****/
		//Calculates the number of 'pages' or 'screens' of products
		//in the scrolling list in order to inject the proper number
		//of page links for the navigation widget.
		
		var numPages = ((listWidth / scrollInterval).toInt())+1;
	
		if (numPages > 1) {
	
			var productCounter = document.getElement('#productpages');	
		
			//Loop through the pages and inject markup
			for (i=numPages; i>0; i--) {
			
					var counterWidget  = new Element('li', {id:'p_'+i} );
					var counterRef = new Element('a');
					counterWidget.inject(productCounter, 'top');
					counterRef.appendText(i).setProperty('href','#').inject($('p_'+i, 'top'));
			
			}
		
			//set initial values for list controls
			$('scrollnext').store('active',true);
			$('scrollprev').store('active',false);
			$('scrollprev').setStyle('opacity','.2');
			updatePageStatus(scrollInterval);

		
		} else {
		
			
			//set initial values for list controls
			$('scrollnext').store('active',false);
			$('scrollprev').store('active',false);
			$('scrollprev').setStyle('opacity','.2');
			$('scrollnext').setStyle('opacity','.2');
	
		}
		
		//close if numPage >1
		
		
		//setup the scroll for direct page links
		
		var pagelinks = document.getElements('#productpages li a');
		
		pagelinks.each  (function(el) {
		
			el.addEvent('click', function() {
							
				//get the page number and calculate jumpto distance
				var jumpNum = el.get('text')-1;
				var jumpDistance = -(jumpNum * scrollInterval);
				
				//scroll to jumpdistance and set marker as current
				scrollProducts(-1, scrollInterval, jumpDistance);
				
				return false;
			});
		
		});	
		
	} //if ul.itemlist
	
	

//setup product listing controls actions


	if (document.getElement('#listcontrols')) {
	
		$('scrollnext').addEvent('click', function(){ 
			
			if ($('scrollnext').retrieve('active')){ scrollProducts(-1, scrollInterval, 'false'); }
			return false; 
			
		});
		
		$('scrollprev').addEvent('click', function(){ 
		
			if ($('scrollprev').retrieve('active')){ scrollProducts(1, scrollInterval, 'false'); }
			return false;
		});
		
	
	} //end if listcontrols



	
	
//Setup the product filter panel

	if ($('filterpanel')) {
	
		var refine = document.getElement('a#filtercontrol');	
		var cancel = $('filtercancel');
		var panel = $('filterpanel');
		if (!Browser.Engine.trident) {
			var retract = panel.getStyle('top').toInt()/10+'em';
		} else {
			var retract = panel.getStyle('top'); 
		}
		var filterFx = new Fx.Tween(panel, {duration:400, unit:'em', transition:Fx.Transitions.Cubic.easeOut});	
		
		refine.addEvent('click', function() { filterFx.start('top',0); });
		cancel.addEvent('click', function() { filterFx.start('top',retract);	});	
	
	}	
	
	
//Setup the diamondsearch button

	if ($('diamondsearch')) {
		var dsFX = new Fx.Morph($('diamondsearch'), {duration:500, transition:Fx.Transitions.Cubic.easeOut});
		$('diamondsearch').setStyles({'top':-100,'display':'block'});
		dsFX.start.delay(2500, dsFX, {'top':10});
	}


//Setup Subpage Promos

if (document.getElement('.subpromo')){
	var subPromo = document.getElement('.subpromo');
	var subPromoFx = new Fx.Morph(subPromo, {transition:Fx.Transitions.Quart.easeOut, link:'cancel', duration:'1000'});
	subPromo.setStyle('right',-300);
	subPromoFx.start.delay(1500, subPromoFx, {'right':10});
}


//************* FOUR C's Section *****************	
	
//Setup the clicks and scrolls for each of the 4 sections

																														/* !cccc */	

if ($('cccc_home')) {


	var cccclinks = document.getElements('dl.fourc dt');
	var slidecontent = new Fx.Tween($('content_wrapper'), {
		duration:600, unit:'em', 
		transition:Fx.Transitions.Quart.easeInOut,
		onComplete: function() { 
			
			setNav4c(); //This function manages the injection and disposal of 4c navigation controls 
			
			}

		});
	 
	 
		 
	cccclinks.each (function(element){
	
		element.addEvent('click', function() {
		
			//Calculate the jumpto distance by retrieving the 'left'
			//distance of the selected subsection
			section = 'cccc_' + element.getProperty('id');
			jumpTo = -(($(section).getStyle('left').toInt())/10);			
			
			//IE reports left position in ems while the rest of the world
			//reports in pixels so compensate
	 		if(Browser.Engine.trident){
	 		
	 			jumpTo = (jumpTo*10)+'em';
	 		
	 		} else {
	 			
 				jumpTo = (jumpTo)+'em';
	 		}
			slidecontent.start('margin-left',jumpTo);
			
			return false;
					
		});
	
	});


	//Setup scrollers for each of the text areas within each subpage

	var scrollers = document.getElements('.scrollable');
	var slider = [];
	var i=0;
	
	scrollers.each (function(element, i){
	
		scrollInterval = element.getCoordinates().height;
		contentSize = element.getScrollSize().y;
		
		if (contentSize > scrollInterval) {

			var scrollerBar  = new Element('div', {id: 'textscroller'+i});
			var scrollerKnob  = new Element('div', {id:'knob'+i});
			scrollerBar.inject(element, 'before');
			$('textscroller'+i).addClass('slider');
			scrollerKnob.inject(scrollerBar);
			$('knob'+i).addClass('knob');
			
	
		// Create the new slider instances	
				slider[i] = new Slider(scrollerBar, scrollerBar.getElement('.knob'), {
				steps: contentSize-scrollInterval,	
				wheel: true,
				mode:  'vertical',
				onChange: function(value){ element.scrollTo(0,value); }
			});

		i++;
	
		}
	
	
	});
	
	
	
	 function setNav4c() {
	
		//First inject 'Back to 4c home' markup if necessary
		
			if(!$('nav4c_home')) {
		
			var homeAnchor = new Element('a', {
				'href': '#', 
				'html': '&laquo; Back to 4c&rsquo;s Home',
				'events' : 
					{ 'click': function() { 
						//User clicked 'back to home' so reset section
						//to first .subpage dom element and
						//reset margin to zero
						section = document.getElement('.subpage');
						slidecontent.start('margin-left',0); 
						}}
				
				});
	
				var homeLi = new Element('li', {'id':'nav4c_home'});
				homeAnchor.inject(homeLi);
				homeLi.inject($('cccc_nav'), 'top');
	
	
			} else {
			
				if ($(section).getProperty('id') == "cccc_home") {$('nav4c_home').dispose(); } 
			
			} //end if nav4c_home
	
		
	
		//Now calculate next section and inject 'Next' markup if necessary
		
		
		var nextSection = $(section).getNext('.subpage'); 
		
		//only setup and inject the 'Next' markup if we are not at either extents
		if ((nextSection) && ($(section).getProperty('id') != "cccc_home")) {
	
			var nextPrompt = nextSection.getElement('h3').get('text');
			var nextJump = -((nextSection.getStyle('left').toInt())/10)+'em'; 
			
			//create the dom elements and inject
			var nextAnchor = new Element('a', {
				'href': '#', 
				'html': 'Next: '+nextPrompt+' &raquo;',
				'events' : 
					{ 'click': function() { 
						section = nextSection;
						slidecontent.start('margin-left',nextJump); }}
				});
			
			
			var nextLi = new Element('li', {'id':'nav4c_next'});
			nextAnchor.inject(nextLi);
					
			//insert the newly created element as a child of cccc_nav
			//only if the 'nextLi' element doesn't already exist.
			//If it does, replace it instead.
			if ($('nav4c_next')){
				nextLi.replaces($('nav4c_next'));
			} else {
				$('cccc_nav').grab(nextLi);
			}		
	
		} else {
		
			if ($('nav4c_next')){ $('nav4c_next').dispose(); }
		
		} //end if nextSection
	
	} //end function setNav4c

} // end 4cs section if	
//******************************	
	


});  //End onLoad handler
// ********************************************************************	


// GLOBAL FUNCTIONS

//Distributes items in a horizontal list evenly to a specified width.  

function distributeItems(containerWidth, elements) {

	var totalEls = elements.length-1;
	var totalPad = ((containerWidth -  totalWidth()).toInt());	
	var pad = ((totalPad / totalEls)/2).toInt();
	
	var count = 0;
	elements.each (function(el) {
		if (count == 0) { el.setStyles({'padding-left':0,'padding-right':pad}); }
		if (count > 0 && count < elements.length) { el.setStyles({'padding-left':pad, 'padding-right':pad}); }
		if (count == elements.length-1) { el.setStyles({'padding-left':pad, 'padding-right':0});}
		count++;		
	});

	function totalWidth() {
		var width = 0;
		elements.each (function(el) { width += el.getSize().x.toInt(); });
		return width;
	}

}

//Diamond Search global functions:
function checkAllCheckboxes(items){
		items.each(function(item) {
		item.setProperty('checked', 'checked');
		});
}

function UncheckAllCheckboxes(items){
		items.each(function(item) {
		item.setProperty('checked', false);
		});
}


function validate_required(field,alerttxt){
	with (field) {
 	 if (value==null||value==" Your email address"){
    alert(alerttxt);return false;
    } else {
   	 return true;
    	}
 	 }
}

function validate_form(thisform){
	with (thisform){
  		if (validate_required(email,"Please supply either an email address or phone number.")==false){
  		email.focus();return false;} else {  
  			alert("Thank your your request.");
  			}
  		}
}



//The fade looping function
//Cycles through a set of dom elements using fade in / fade out animations
//Takes list (an array of dom elements, interval (the number of milliseconds per loop), 
//and a unique name for the interval so it can be stopped later.
//Style is either 'crossfade' or 'popfade'	

function fadeLoop(list, interval, style, loopName) {
	
	var i  = 1;
	if (style=='crossfade') {
		var fadecode = "fade('out')";
	} else {
		var fadecode = "setStyles({'display':'none','opacity':0})";
	}
	
	list[0].setStyles({'display':'block','opacity':1});

	var showItems = function () {
		if (i==0){
			list[i].setStyle('display','block');
			list[i].fade('in');
			fadecommand = 'list.getLast().'+fadecode;
			eval(fadecommand);
		} else {
			fadecommand = 'list[i-1].'+fadecode;
			eval(fadecommand);
		}
		list[i].setStyle('display','block');
		list[i].fade('in');
		i++;
		if (i>=list.length) { i = 0 };
	}

	this[loopName] = showItems.periodical(interval);
	//this convention provides a method to call or set
	//a function using a variable name.
}



function vCenter (container, content)
//function to vertically center positioned content elements within a container
{
	//check if params are DOM elements, if not convert them
	if($type(container)!='element') container = document.getElement(container);
	if($type(content)!='element') content = document.getElement(content);
	//Get sizes and calculate
	var containerHeight = container.getSize().y;
	var contentHeight = content.getSize().y;
	var vCenter = ((containerHeight/2) - (contentHeight/2));
	return vCenter;
}


	
function createRecordObject(response)

//Returns a JS object of the found record with
//table fields as properties of the object
//using = and | as delimeters

{

	var qResult = new Object;
	var records = response.split('|');
	
	for (var i = 0;i<records.length;i++)
	{
				
		var properties = records[i].split('=');		
		var key = properties[0];
		var val = properties[1];
		
		qResult[key] = val;
	}
	
	return qResult;
}
		



function currentSection() {

	//The class of div 'wrapper' is the current section
	var currentSection = $('wrapper').getProperty('class');
	return currentSection;
}

function currentSubSection() {
	//The class of div 'plate' is the current subsection
	return $('plate').getProperty('class');
}


function currentPage() {

//For sections with multiple 'pages'
//The class of div 'plate' is the current page

	if (document.getElement('.page')){
	
		var currentPage = $('plate').getProperty('class');
		return currentPage;
	
	} else {
	
		return false;
	
	}
}	


function initScroll() {
	
//Setup any scrollable text controls

	
	//Only inject scroll widgets if content is larger than area
	
	if (showScroll()) { 
				
		//Inject the scroller markup into the HTML
			var scrollerBar  = new Element('div', {id: 'textscroller'});
			var scrollerKnob  = new Element('div', {id:'knob1'});
			
			scrollerBar.inject(scrollArea, 'before');
			$('textscroller').addClass('slider');
			scrollerKnob.inject(scrollerBar);
			$('knob1').addClass('knob');
			
	
		// Create the new slider instance	
			var slider = new Slider($('textscroller'), $('textscroller').getElement('.knob'), {
				steps: contentSize-scrollInterval,	
				wheel: true,
				mode:  'vertical',
				onChange: function(value){ scrollArea.scrollTo(0,value); }
			});

	
		// Set the newly injected scroller object to transparent in 
		// anticipation of its fade-in after the scanner stops
		
			$('textscroller').setStyle('opacity','0');

		//Instatiate the textscroller FX object for use in other functions
			scrollerFx = new Fx.Tween($('textscroller'), {duration:1000, transition:Fx.Transitions.Cubic.easeOut, link:'chain'}) 
	
	} else {
	
		//if the content size is smaller than the scroll area
		//don't show the scrollbar.  But we need to check if
		//the scrollbar markup has already been injected from 
		//another page's content.  If it has, remove it.
			
		if ($('textscroller')) { $('textscroller').dispose(); }
	
	}

		
} //end initScroll


function showScroll() {

	//Function to determine whether or not a scrollbar should be shown
	
	//first check if there is a .scrollable element
	if (document.getElement('.scrollable')){
	

		//Check if there is multi-page content in the section
		//and if so, select the correct scrollable area based on 
		//the page head id
		//if not set scrollarea to the first .scrollable element.
		
		if (currentPage() != false ) {
			scrollArea = document.getElement('.'+currentPage()+' .scrollable');
		} else {
			scrollArea = document.getElement('.scrollable');
		}
	
		scrollInterval = scrollArea.getCoordinates().height;
		contentSize = scrollArea.getScrollSize().y;
	
		//Only display scroll widgets if content is larger than area
	
		if (contentSize > scrollInterval) {
		
			return true;
			
		} else {
		
			return false;
		} 
	
	} else {
	
		return false;
		
	}

}


function hidePages() {

	//if there is multipage content, this function
	//hides all pages to allow for fadein
	//We call this on domReady and initPages on dom load.
	
	if (document.getElement('.page')) {

	var pages = $$('.page');

	pages.each (function(element){	
	
			//hide all pages 
			element.setStyles({ 'display':'none',
								'opacity':'0',
								'margin-top':'0' });
		
		});

	
	//Hide any image captions if they exits

		if (document.getElement('.caption')) {
	
		var captions = $$('.caption');
	
		captions.each (function(element){	
		
				element.setStyles({ 'display':'none' });
			
			});
		
		}

	}

}


function initPages(){
//function to initialize non-jewlery listing pages
//(news, services, etc)
	
	//Check if this is a non-jewelry listing page		
	if (document.getElement('.page')) {

		hidePages();


		if (window.location.hash.substring(1) != "") {
			//entered page with a product anchor so grab
			//the anchor -- the sku-- and display
			//var type = window.location.hash.substring(1).split("_")[1];
			var type = window.location.hash.split("#")[1];
			$('plate').removeProperty('class');
			$('plate').addClass(type);
		}

		
		//Fade in the current Page
		$(currentPage()).setStyle('display','block');
		fadeFx = new Fx.Tween($(currentPage()), {duration:500});
		fadeFx.start('opacity','1');


	//setup the Scroller for paged content
	
	
		initScroll();
	
	
		//Fade in scroller if present
		if(showScroll()) {

			scrollerFx.start('opacity','1');
		}	


	//Check if any image links exist on the pages and initialize if necessary
	
	initImageViewer();

}	
	
} //end initPages




function initImageViewer(){


	if ($('captionarea')) { 
		var captionArea = $('captionarea');
		captionArea.setStyle('opacity','0'); 
		captionFx = new Fx.Tween(captionArea, {duration:500});
	}

	if (document.getElement('.imagelinks')) {
	
	
		var imagePath = "_images/"+currentSection()+"/";
		var displayArea = $('displayarea');
	
	
	
		//Check to see if the first 'story' of the 'page' has an image
		//if so, we want to display it, if not, display the default image
	
		if (document.getElement('#'+currentPage()+ ' .imagelinks li a')){
			
			var firstImage = document.getElement('#'+currentPage()+ ' .imagelinks li a');

			//clear the onload function that may be set from clicking on imagelinks 
			//from previous content 'pages'.  This prevents the previous caption from 
			//being shown 	
			displayArea.onload = function(){};
			
			displayArea.set('src',firstImage.getProperty('href'));
			if(captionArea){
				captionArea.setStyle('opacity','0'); 
			};
			
	
		} else {
		
			displayArea.set('src',imagePath+'default.jpg');
		
		}
	
	
		//Hide all imagelink areas for stories with only 1 image
		
		var stories = $$('.story');
		
		stories.each(function(story){
			if(story.getElement('.imagelinks')){
				var imagelinks = story.getElements('.imagelinks li a');
				if(imagelinks.length <= 1){
					story.getElement('.imagelinks').setStyle('display','none');		
				}
			}
		});
	
	
		var preloadFx = [];
		var postloadFx = [];
		var i = 0;
	
		var imagesLinks = $$('.imagelinks li a');
		
 
		imagesLinks.each (function(element, i){	


		preloadFx[i+1] = new Fx.Tween(displayArea, {duration:500});
		postloadFx[i+1] = new Fx.Tween(displayArea, {duration:500});
		
		
		element.addEvent('click', function() {
	
					//Fade out image and caption areas
					preloadFx[i].start('opacity','0');
					captionFx.start('opacity','0');

					$('plate').addClass('loading');							
					
					//change them image src and caption text after the fadeout
					preloadFx[i].addEvent('complete',  function(){
														
						//set the image area source to the new image
						displayArea.erase('src');
						displayArea.set('src',element.getProperty('href'));

						//If a caption exists, grab the text and set inject it into the captionArea element 		
						if (element.getProperty('title')!="") {
							var captionText = element.getProperty('title');			
							captionArea.set('text',captionText);
						
						} else {
						
							captionArea.set('text','');
		
						}			
				
						//Fade in the image and caption only after the image has loaded
						displayArea.onload = function () { 
							
							postloadFx[i].start('opacity','1');  
							if (element.getProperty('title')) { captionFx.start('opacity','.8'); } 
				
						}
				
				
					 });
						
				return false;
			});

		i++;
		
		});	
	
	}  // close main if

} // end iniImageViewer




function initScanner() {

	 //SCANNER ANIMATION
		
	//Determine Scanner stopping points based on th existence of div 'block_scanner'
	//and checking to see if it is already prepositioned in the CSS using the 'left' attibute 
	//if it is aleady positioned, then use the existing left value of the element as
	//the scanner's stopping point. If not, get the width of the text content box und use that
	// as the stopping point
	//We're dividing by 10 to convert to ems


	if (document.getElement('.block_scanner')) {
	

	var offset = 1.7;
	
	
	if (document.getElement('.block_text')){ 
		var textBoxWidth = (document.getElement('.block_text').getCoordinates().width); 
		}
	
	   scanner = document.getElement('.block_scanner');
		scannerFx = new Fx.Tween(scanner, {duration:1700, transition:Fx.Transitions.Cubic.easeOut, unit:'em', link:'chain'});
	 
	 //first check if a scanner div exists
	 if (scanner) {
	 
	 	//Check if it is already positioned
	 
	 	//Mozilla reports unpositioned objects as 0px while the rest report 'auto' 
	 	//so account for this in the if statement
	 	if (scanner.getStyle('left') != 'auto' && scanner.getStyle('left') != '0px') {
	 	
	 		//It is prepositioned, so use that value for the animation stopping point
			//But ie reports the left value as ems but the rest report
			//as pixels, so first check for ie and set property accordingly
				 		
	 		if(Browser.Engine.trident){
	 		
	 			scannerEndPos = (scanner.getStyle('left'));
	 		
	 		} else {
	 		
	 			scannerEndPos = (scanner.getStyle('left').toInt()/10+'em');
	 			
 		
	 		}
	 	
	 			
	 	} else { 
	 	
	 		//It's not prepositioned so use the text box width minus an offset for page specific positiong
	 		scannerEndPos = (textBoxWidth/10) - offset; //Convert to ems then subtract offset to have it overlap a bit

 		
		}
	
	 } else {
	 
	 	//we may ultimately inject a scanner but we don't know yet
	 	//It would go here, if we decide to do it.

	 }
	
	//Now Position the Scanner Box offscreen, set opacity
	//and display value, in preparation for slidein
	
	scanner.setStyles({ 	
	
						'left':'96em', 
						'display':'block', 
						'opacity':'.6'
						
					  }); 

	} //end if

} //end initScanner
	
	
	


function displayMainImage(imagePath, imageTag, sku, desc) 

{
	
	//First set the src to blank in case the user clicks
	//on the same image twice, which would otherwise
	//prevent the onload event from firing
	$(imageTag).set('src','');
	
	//Remove any detail thumbnails from previous pieces if they exists
	if($('detailThumbs')) {	$('detailThumbs').dispose(); }


	//We need to grab the filename from the products table
	//based on the sku, so setup an AJAX request
	//On success of the request call the function to
	//set the src of the image area and description
	
	var requestFilename = new Request 
	({
		method: 'get',
		url: './_library/ajax.php',
		onSuccess: function(responseText) { setSrcAndDesc(imagePath+responseText, desc);  },
		onFailure: function(xhr) {alert(xhr); }				
	
	});
	

	
	//Send the request: 'type' is the name of the function in 'ajax.php'	
	requestFilename.send('type=skuToFilename&sku='+sku);

	
	 
	 //Setup the AJAX request for detail images
	 var requestDetails = new Request
	 	({
	 		method: 'get', 
	 		url: './_library/ajax.php',
	 		onSuccess: function(responseText) { displayDetails(imagePath, responseText, sku); }, 
	 		onFailure: function(xhr) {alert(xhr);}						
	 	});

	//Send the request: 'type' is the name of the function in 'ajax.php'
	 requestDetails.send('type=checkForFile&sku='+sku+'&suffix=_sm');


	 //Setup the AJAX request for large images
	 var requestZooms = new Request
	 	({
	 		method: 'get', 
	 		url: './_library/ajax.php',
	 		onSuccess: function(responseText) { displayZoom(responseText); }, 
	 		onFailure: function(xhr) {alert(xhr);}						
	 	});

	//Send the request: 'type' is the name of the function in 'ajax.php'
	 requestZooms.send('type=checkForZoom&sku='+sku);

	//Setup Print and email links
	$('printlink').setProperty('href','print.php?sku='+sku);
	$('printlink').setProperty('target','_blank');


}



function setSrcAndDesc (filename, desc)
//Function to set the src and desc of the image to be displayed
//uses the repsonse text from the AJAX request 'requestFilename' 

{
	var source = filename+'_md.jpg';
	var zoomSource = filename+'_lg.jpg';
	
	//add large image href and title
	//properties for milkbox
	$('zoomlink').set('href',zoomSource);
	$('zoomlink').setProperty('title',desc);
	milkbox.reloadGalleries();
	
	$(imageTag).set('src',source).onload = function() { 

		//Fade in the main image
		 imageFx.start('opacity','1'); 	
		 //Inject description into main description area
		document.getElement('#description').set('html', desc);	 
		$('description').fade('in');
		//Quick fix for description text that intrudes into the
		//detail image thumbnails
		if ($('description').getSize().y.toInt() >=250) {
			$('detailThumbs').setStyle('display','none');
		} else {
			$('detailThumbs').setStyle('display','block');
		} 
	
	 }


}


function displayZoom(response)
//Function to display zoom icon if a large image was found
//uses the repsonse text from the previous AJAX request
{

	if (response) { 
		$('zoomlink').setStyle('display','block'); 
	} else {
		$('zoomlink').setStyle('display','none'); 
	}

}


function displayDetails(imagePath, response, sku) 
//Function to display detail images if any
//uses the repsonse text from the previous AJAX request

{

	//Parse the response text and create a JS object of the key/value pairs
	var qResult = createRecordObject(response);
	
	//instantiate the ul element that will contain the detail tumbnails
	var detailThumbUl = new Element('ul', {'id':'detailThumbs'});

	//loop through all of the key/value pairs of the reponse object
	for (i in qResult ){
	
		//only create a detail thubnail li element if the value is true
		//i.e. the ajax script has determined the detail jpeg file exists
		if (qResult[i]=='true') {

			//all detail shots suffixed with 0 are treated as links back to the
			//main full-size image, so check for 0 and assign the filename
			//of the main image, rather than a detail image
			if (i == 0) {
				detailFileName = sku+'_md.jpg';
			} else {
				detailFileName = sku+'_'+i+'_md.jpg';						
			}
	
			//create the dom elements and inject
			var detailThumbLi = new Element('li');
			
			//create the img element and add the click
			//event for loading the full size detail image
			var detailThumbImg = new Element('img', {
				'id':'detail'+i,
				'href': '#'+sku,
				'src': imagePath+sku+'_'+i+'_sm.jpg',
				'events' : 
					{ 'click': function() { 
						mainImage.setStyle('opacity',0);
						
						//call the displayDetail function and pass it
						//this detail element.  We use the '.store' method
						//to embed the fullsize filename into the object
						displayFullDetail('displayarea', this); }}
				}).store('filename', imagePath+detailFileName);
				
			//Inject the img into the li
			detailThumbImg.inject(detailThumbLi);
			
			//Inject the li into the ul
			detailThumbLi.inject(detailThumbUl);
		}

	}
	//inject the ul into the main markup
	detailThumbUl.inject($('description'), 'after');
}



function displayFullDetail(imageTag, obj) {
	
	//First set the src to blank in case the user clicks
	//on the same image twice, which would otherwise
	//prevent the onload event from firing
	$(imageTag).set('src','');

	//retrieve the stored filename property and set the src to it
	var source = $(obj).retrieve('filename');
	$(imageTag).set('src',source).onload = function() { 
	
		//Fade in the main image
		 imageFx.start('opacity','1'); 	
	
	 }
	 	

}




	
	
function scrollProducts(direction, scrollInterval, jumpTo){

	
		var contentSize = (itemsUl.getSize().x)/10;
		var currPos = itemsUl.getStyle('margin-left').toInt();		
		var scrollDistance = direction * scrollInterval;		
		
		if (jumpTo == 'false') {
		
			var newPos = currPos + scrollDistance;
		
		} else {
		
			var newPos = jumpTo;
		
		}
		
				
		itemsSlide.start('margin-left', newPos);

		
		
		var nextPos = newPos+scrollDistance;

		if ( -(nextPos)  >= contentSize){

			$('scrollnext').setStyle('opacity','.2');
			$('scrollnext').store('active',false);
		
		} else {

			$('scrollnext').setStyle('opacity','1');
			$('scrollnext').store('active',true);
		
		}



		if ( newPos  >= 0){

			$('scrollprev').setStyle('opacity','.2');
			$('scrollprev').store('active',false);
		
		} else {

			$('scrollprev').setStyle('opacity','1');
			$('scrollprev').store('active',true);
		}
						
		

}	//end scrollProducts



function updatePageStatus(scrollInterval) {

	//clear any previously highlited page marker
	var selected = document.getElement('.current');
	if(selected){selected.removeClass('current');}
	
	//now calcute currentpage and set highlight
	var currPos = itemsUl.getStyle('margin-left').toInt();
	var currPage = 	(-(currPos/scrollInterval))+1;
	var currentPageId = 'p_'+currPage;
	if($(currentPageId)){ $(currentPageId).getFirst('a').addClass('current');}

}


function showSecondaryNav()
{

	//Fade in secondary Nav if available
	if(document.getElement('#secondary.sidenav')) { navFx.start('opacity','1'); }	
	if(document.getElement('#secondary p.comingsoon')) { navFx.start('opacity','.6'); }	
	if(document.getElement('#secondary ul.nav')) { navFx.start('opacity','.9'); }	

	//Fade in scroller if present
	if($('textscroller')) { scrollerFx.start('opacity','1'); }	


}







