/*
Copyright (c) 2009, All rights reserved.
Code licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php

Author: Draftfcb Chicago
Developer: scott.boyce@draftfcb.com
*/

var HTML5 = new Class({
	Implements: Options,
	options: {
	},
	initialize: function(options) {
		this.setOptions(options);
		this.formatLinks();
		this.formatInputs();
	},
	printpage: function() {
		if (window.print) {
			window.print();
		} else {
			alert("Sorry, your browser doesn\u0027t support this feature. Please print from your browser\u0027s \u201DPrint\u2026\u201C menu.");
		}
	},
	formatLinks: function() {
		$$('a').each(function(item) {
			switch (item.getProperty('rel')) {
				case 'external':
					// tracking goes here
					// item.setProperty('target', '_blank');
				break;
				case 'print':
					item.addEvent('click', function(e) {
						e.stop();
						this.printPage();
						item.blur();
					}.bind(this));
				break;
				case 'info':
					item.setProperties({
						'title': item.getProperty('html'),
						'html': 'More Info&nbsp;\u00BB'
					});
				break;
				case 'details':
					item.setProperties({
						'title': item.getProperty('html'),
						'html': 'More Details&nbsp;\u00BB'
					});
				break;
			}
		}, this);
	},
	formatInputs: function() {
		// convert unsupported type="" values to type="text"
		$$('input').each(function(l) {
			switch (l.getProperty('type')) {
				case 'text':
					l.setProperty('type', 'text');
					break;
				case 'email':
					if (!Modernizr.inputtypes.email) {
						l.setProperty('type', 'text');
					}
					break;
				case 'search':
					if (!Modernizr.inputtypes.search) {
						l.setProperty('type', 'text');
					}
					break;
			}
		});
		// convert placeholder="foobar" to value="foobar"
		$$('input').each(function(l) {
			if (l.getProperty('placeholder')) {
				l.addClass('placeholder').setProperty('value', l.getProperty('placeholder')).addEvents({
					'focus': function() {
						l.removeClass('placeholder');
						if (l.getProperty('value') == l.getProperty('placeholder')) {
							l.setProperty('value', '');
						}
					},
					'blur': function() {
						if (l.getProperty('value') == '') {
							l.setProperty('value', l.getProperty('placeholder')).addClass('placeholder');
						}
					}
				});
			}
		});
		// convert placeholder="foobar" to value="foobar"
		$$('textarea').each(function(l) {
			if (l.getProperty('placeholder')) {
				l.addClass('placeholder').setProperty('value', l.getProperty('placeholder')).addEvents({
					'focus': function() {
						l.removeClass('placeholder');
						if (l.getProperty('value') == l.getProperty('placeholder')) {
							l.setProperty('value', '');
						}
					},
					'blur': function() {
						if (l.getProperty('value') == '') {
							l.setProperty('value', l.getProperty('placeholder')).addClass('placeholder');
						}
					}
				});
			}
		});
	}
});
var detailsBox = new Class({
	Implements: Options,
	options: {
		container: 'details',
		about: 'about',
		palettes: 'palettes'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.container = $(this.options.container);
		this.about = $(this.options.about);
		this.palettes = $(this.options.palettes);
		if ($chk(this.container)) {
			this.createButtons();
		}
	},
	createButtons: function() {
		// redundant setStyle calls because IE6 doesn't properly add/remove .hidden class
		this.about.getChildren('h1').addEvent('click', function(e) {
			e.stop();
			this.about.addClass('hidden');
			this.about.setStyle('display', 'none');
			this.palettes.removeClass('hidden');
			this.palettes.setStyle('display', 'block');
			e.target.blur();
			try
			{
			    var productPageUrl =$('productHelperContainer').getElements('input[name$=hdnProductUrl]')[0].value + '/colorpalette';
                if(pageTracker == undefined)
                {
                    pageTracker = _gat._getTracker("UA-12931684-1");
                }
                pageTracker._trackPageview(productPageUrl);
            } catch(err) {}
			// IE6 render bug workaround (pngfix causes lightfastness stars to lose position until rerender)
			$('color0').fireEvent('click');
		}.bind(this));
		this.palettes.getChildren('h1').addEvent('click', function(e) {
			e.stop();
			this.palettes.addClass('hidden');
			this.palettes.setStyle('display', 'none');
			this.about.removeClass('hidden');
			this.about.setStyle('display', 'block');
			e.target.blur();
			try
			{
			    var productPageUrl =$('productHelperContainer').getElements('input[name$=hdnProductUrl]')[0].value + '/about';
                if(pageTracker == undefined)
                {
                    pageTracker = _gat._getTracker("UA-12931684-1");
                }
                pageTracker._trackPageview(productPageUrl);
            } catch(err) {}
		}.bind(this));
	}
});
// DHTML functions for studio forms
var studioFormDynamics = new Class({
	Implements: Options,
	options: {
		container: $('webform'),
		productSubSections: $$('.productSubSection')
	},
	initialize: function(options) {
		this.setOptions(options);
		if ($chk(this.options.container)) {
			this.createProductCheckboxEvents();
		}
	},
	// expand/contract 'product used' subsection checkboxes in studio-upload.aspx
	createProductCheckboxEvents: function() {
		this.options.productSubSections.each(function(section){
			// find the main checkbox, e.g. id of "product00"
			parentCheckbox = section.getFirst().getFirst().getFirst();
			parentCheckbox.addEvent('click', function(e){
				parentLabel = this.getParent();
				// find the dependent checkboxes
				siblingSubSectionCheckboxes = parentLabel.getParent().getAllNext('.subSection');
				if (this.getProperty('checked')) {
					parentLabel.addClass('checked');
					siblingSubSectionCheckboxes.each(function(item){ item.removeClass('hidden'); });
				} else {
					parentLabel.removeClass('checked');
					siblingSubSectionCheckboxes.each(function(item){ item.addClass('hidden'); });
				}
			});
		});
	}
});

var artistTabs = new Class({
	Implements: Options,
	options: {
		tabnav: 'tabnav', //$('tabnav')
		container: 'artistTabs', //$('artistTabs')
		buttonFavorite: 'tabnav00', //$('tabnav00')
		buttonTips: 'tabnav01', //$('tabnav01')
		buttonInterview: 'tabnav02', //$('tabnav02')
		favorite: 'tabFavoriteContainer', //$('tabFavoriteContainer')
		tips: 'tabTipsContainer', //$('tabTipsContainer')
		interview: 'tabInterviewContainer' //$('tabInterviewContainer')
	},
	initialize: function(options) {
		this.setOptions(options);
		this.tabnav = $(this.options.tabnav);
		this.container = $(this.options.container);
		this.buttonFavorite = $(this.options.buttonFavorite);
		this.buttonTips = $(this.options.buttonTips);
		this.buttonInterview = $(this.options.buttonInterview);
		this.favorite = $(this.options.favorite);
		this.tips = $(this.options.tips);
		this.interview = $(this.options.interview);
		this.footer = $('all').getElement('footer');
		
		if ($chk(this.container)) {
			this.createButtonEvents();
		}
	},
	createButtonEvents: function() {
		this.buttonFavorite.addEvent('click', function(e) {
			e.stop();
			this.switchTab(this.favorite);
			e.target.blur();
		}.bind(this));
		this.buttonTips.addEvent('click', function(e) {
			e.stop();
			this.switchTab(this.tips);
			e.target.blur();
		}.bind(this));
		this.buttonInterview.addEvent('click', function(e) {
			e.stop();
			this.switchTab(this.interview);
			e.target.blur();
		}.bind(this));
	},
	switchTab: function(onTab) {
		this.favorite.addClass('hidden');
		this.tips.addClass('hidden');
		this.interview.addClass('hidden');
		switch (onTab.getProperty('id')) {
			default:
			case 'tabFavoriteContainer':
				this.tabnav.setStyle('background-position', '0 0');
				this.footer.setStyle('display', 'none');
				this.footer.setStyle('display', 'block');
			break;
			case 'tabTipsContainer':
				this.tabnav.setStyle('background-position', '-712px 0');
				this.footer.setStyle('display', 'none');
				this.footer.setStyle('display', 'block');
			break;
			case 'tabInterviewContainer':
				this.tabnav.setStyle('background-position', '-1421px 0');
				this.footer.setStyle('display', 'none');
				this.footer.setStyle('display', 'block');
			break;
		}
		onTab.toggleClass('hidden');
	}
});

var artistCarousel = new Class({
	Implements: Options,
	options: {
		container: 'artistCarousel', //$('artistCarousel'),
		btnLeft: 'btnLeft', //$('btnLeft'),
		btnRight: 'btnRight', //$('btnRight'),
		pieceWidth: 419, // in px, total width of li including padding/margin
		pieceChangePeriod: 10000 // time to wait before changing to a random piece, in milliseconds
	},
	initialize: function(options) {
		this.container = $(this.options.container);
		this.btnLeft = $(this.options.btnLeft);
		this.btnRight = $(this.options.btnRight);
		this.setOptions(options);
		if ($chk(this.container)) {
			this.setupCarousel();
		}
	},
	setupCarousel: function() {
		var self = this;
		var theList = this.container.getFirst();
		var pieces = theList.getChildren('li');
		//console.log('pieces: ', pieces);
		var pieceAnchors = $$('.pieceAnchor');
		//console.log('piece anchors: ', pieceAnchors);
		var numPieces = pieces.length;
		//console.log('num pieces: ', numPieces);
		var currentPiece = 3;
		var currentMargin = 0;
		var firstViewFlag = true;
		var timerInterval = this.options.pieceChangePeriod;
		var increment = this.options.pieceWidth;
		var viewPortWidth = this.container.getStyle('width').toInt();
		//console.log('viewport width: ', viewPortWidth);
		var viewPortOffset = viewPortWidth / 2 - this.options.pieceWidth / 2;
		var copyElements = [theList.getElementsByTagName('h2'), theList.getElementsByTagName('p')];
		copyElements = copyElements.flatten();
		//console.log('copy elements: ', copyElements);
		
		//set width of parent ul element to match sum width of list items
		theList.setStyle('width', numPieces * this.options.pieceWidth);
		//console.log('num pieces: ', numPieces, ' ul width: ', theList.getStyle('width'));
		
		// initially hide all copy elements
		self.hideAllCopy(copyElements);

		var fx = new Fx.Tween(theList, {
			property: 'margin-left',
			duration: 750, // milliseconds
			transition: Fx.Transitions.Quad.easeInOut,
			link: 'ignore'
		});
		
		// do not run timer while mouse is over container
		this.container.addEvents({
			'mouseenter': function() {
				// clear the timer function
				$clear(timerSlide);
			},
			'mouseleave': function() {
				// begin a new timer function
				beginTimerSlide();
			}
		});
		
		// periodical slide increment
		var timerSlide;
		var beginTimerSlide = function() {
			timerSlide = (function() {
				// increment slides every timerInterval seconds
				if (currentPiece < numPieces) {
					currentPiece += 1;
				} else {
					currentPiece = 1;
				}
				currentMargin = -(increment - viewPortOffset + (currentPiece - 1) * increment);
				//console.log('initial margin: ', currentMargin);
				
				//theList.setStyle('margin-left', currentMargin);
				fx.start(currentMargin);
				
				// reset copy elements to hidden
				self.hideAllCopy(copyElements);
				// show copy elements on focused piece
				pieces[currentPiece - 1].getChildren('.hidden').removeClass('hidden');
			}).periodical(timerInterval);
		}
		
		// pick a random piece and show immediately, but do not land on first or last image
		currentPiece = $random(2, numPieces - 1);
		currentMargin = -(increment - viewPortOffset + (currentPiece - 1) * increment);
		fx.start(currentMargin);
		pieces[currentPiece - 1].getChildren('.hidden').removeClass('hidden');

		// start periodical function
		beginTimerSlide();
		
		// set events for image anchors
		for (var i = 0; i < numPieces; i++) {
			var theAnchor = pieces[i].getFirst('.pieceAnchor');
			theAnchor.store('index', i + 1);
			//console.log('the anchor: ', theAnchor);
			theAnchor.addEvent('click', function(e) {
				e.stop();
				fx.cancel();
				currentPiece = this.retrieve('index');
				currentMargin = -(increment - viewPortOffset + (currentPiece - 1) * increment);
				self.hideAllCopy(copyElements);
				fx.start(currentMargin);
				// show copy elements on focused piece
				pieces[currentPiece - 1].getChildren('.hidden').removeClass('hidden');
				//console.log('anchor click');
				//console.log('current piece: ', currentPiece);
			});
		}		
				
		this.btnLeft.addEvent('click', function(e) {
			e.stop();
			if (currentPiece > 1) {
				fx.cancel();
				currentMargin += increment;
				currentPiece -= 1;
				self.hideAllCopy(copyElements);
				fx.start(currentMargin);
				// show copy elements on focused piece
				pieces[currentPiece - 1].getChildren('.hidden').removeClass('hidden');
			}
			//console.log('current piece: ', currentPiece);
		});
		this.btnRight.addEvent('click', function(e) {
			e.stop();
			if (currentPiece < numPieces) {
				fx.cancel();
				currentMargin -= increment;
				currentPiece += 1;
				self.hideAllCopy(copyElements);
				fx.start(currentMargin);
				// show copy elements on focused piece
				pieces[currentPiece - 1].getChildren('.hidden').removeClass('hidden');
			}
			//console.log('current piece: ', currentPiece);
		});
		
	},
	hideAllCopy: function(elements) {
		// hide all copy elements
		elements.each( function(element) {
			$(element).addClass('hidden');
		});
		
	}
});



var slideshow = new Class({
	Implements: Options,
	options: {
		container: $('slideshow'),
		nav: $('slidenav'),
		images: $$('#slideshow img')
	},
	initialize: function(options) {
		this.setOptions(options);
		if ($chk(this.options.container)) {
			this.createLinks();
		}
	},
	createLinks: function() {
		var length = this.options.images.length,
			i = length - 1,
			li = null;
		if (i > 0) { do {
			li = new Element('li', {
				'html': parseInt(i, 10) + 1,
				'events': {
					'click': function(e) {
						e.stop();
						this.options.nav.getChildren('li').removeClass('selected');
						this.toggleSlide(e.target.getProperty('html'));
						e.target.addClass('selected');
					}.bind(this),
					'mouseover': function(e) {
						e.stop();
						this.addClass('hover');
					},
					'mouseout': function(e) {
						e.stop();
						this.removeClass('hover');
					}
				}
			}).inject(this.options.nav, 'top');
			if (i == 0) {
				li.addClass('selected');
			}
		} while (i--);}
	},
	toggleSlide: function(slide) {
		var length = this.options.images.length,
			i = length - 1;
		if (i > 0) { do {
			if (i == slide - 1) {
				this.options.images[i].removeClass('hidden');
			} else {
				this.options.images[i].addClass('hidden');
			}
		} while (i--);}		
	}
});
var paletteChooser = new Class({
    Implements: Options,
    options: {
        container: $('palettes'),
        colorbar: $('colorbar'),
        nav: $('setnav'),
        data: Array()
    },
    initialize: function(options) {
        this.setOptions(options);
        if ($chk(this.options.container)) {
            var count = this.options.nav.getChildren('li')[0].getChildren('span')[0].getProperty('html');
            var colorSetName = this.options.nav.getChildren('li')[0].getProperty('colorSetName');
            this.getData(count, colorSetName);
            this.createNav();
        }
    },
    createNav: function() {
        var length = this.options.nav.getChildren('li').length,
			i = length - 1,
			count = null;
        colorSetName = null;
        if (i > 0) {
            do {
                this.options.nav.getChildren('li')[i].addEvents({
                    'click': function(e) {
                       	if (e) e.stop();
                        this.options.nav.getChildren('li').removeClass('selected');
                        this.options.nav.getChildren('li').setStyle('background-position','0px 0px'); /*IE 6 issue - doesn't apply class*/
                        e.target.setStyle('background-position','0px -40px');
                        count = e.target.getChildren('span')[0].getProperty('html');
                        colorSetName = e.target.getProperty('colorSetName');
                         this.options.container.getChildren('img').addClass('hidden');
                        this.options.container.getChildren('img').setStyle('display','none'); /*IE 6 issue - doesn't apply class*/
                        $('set' + colorSetName).removeClass('hidden');
                        $('set' + colorSetName).setStyle('display','block');/*IE 6 issue - doesn't apply class*/
                        this.getData(count, colorSetName);
                    } .bind(this),
                    'mouseover': function(e) {
                        this.addClass('hover');
                    },
                    'mouseout': function(e) {
                        this.removeClass('hover');
                    }
                });
            } while (i--);
        }
    },
    getData: function(count, colorSetName) {
       
        if (count === undefined || isNaN(count)) {
            count = 12;
        }

        var jsonURL = $('colorSetServiceUrl').getElements('input[name$=hdnPaletteFeedUrl]')[0].value;
        jsonURL += "&cc=" + count + "&csn=" + colorSetName;
        new Request.JSON({
            url: jsonURL,
            method: 'get',
            onRequest: function() {
            } .bind(this),
            onComplete: function(jsonObj, text) {
                this.options.data = jsonObj;
                this.createBars(count);
            } .bind(this)
        }).send('count=' + count);
    },
    createBars: function() {
    var self = this;
        var length = this.options.data.length,
			i = length - 1,
			datum = null,
			li = null,
			count = 0,
			colorbarWidth = 504;
        if ($('hslider')) {
            $('hslider').removeEvents(); //debug dk 030410:1519
            $('hslider').destroy();
        }
        this.options.colorbar.removeEvents(); ////debug dk 030910:1413
        this.options.colorbar.empty();
        this.options.colorbar.setProperty('class', 'count' + length);
        this.options.colorbar.setStyle('background', 'rgb(' + this.options.data[i]['rgb'] + ')');
        if (i > 0) {
            do {
                count = length - i - 1;
                datum = this.options.data[count];

                if (datum != null && datum['id'] == null) {
                    datum['id'] = '';
                }
                li = new Element('li', {
                    'id': 'color' + count,
                    'title': datum['name'] + ' ' + datum['id'],
                    'html': '<div><hgroup><h3>' + datum['name'] + '</h3><h4>' + datum['id'] + '</h4></hgroup><ul><li><abbr title="Red, Green, Blue">RGB</abbr>: ' + datum['rgb'] + '</li><li><abbr title="Cyan, Magenta, Yellow, Black">CMYK</abbr>: ' + datum['cmyk'] + '</li><li class="notes"><em>' + datum['notes'] + '</em></li></ul></div>',
                    'styles': {
                        'background': 'rgb(' + datum['rgb'] + ')',
                        'cursor': 'pointer',
                        'color': datum['textColor']
                    },
                    'events': {
                        'click': function(e) {
                            if (e) e.stop();
                           self.toggleColor(this.getProperty('id'), length);
					    }
                    }
                }).inject(this.options.colorbar);
            } while (i--);
        }
        this.options.colorbar.setStyle('left', '0');
        if (length < 36) {
            this.options.colorbar.setStyle('width', colorbarWidth + 'px');
        } else {
            colorbarWidth = ((10 * (length - 1)) + 154);
            this.options.colorbar.setStyle('width', colorbarWidth + 'px');
            new makeScrollbar(this.options.colorbar);
        }
        this.toggleColor('color0', length);
    },
    toggleColor: function(cid, count) {
        var unselectedWidth = 0,
			selectedWidth = 0,
			colorbarWidth = this.options.colorbar.getSize().x;
        if ($chk($(cid))) {
            switch (count) {
              case 2:
                    unselectedWidth = 252;
                    selectedWidth = 252;
                    break;
              case 4:
                    unselectedWidth = 116;
                    selectedWidth = 156;
                    break;
               case 6:
                    unselectedWidth = 70;
                    selectedWidth = 154;
                    break;
                 case 8:
                    unselectedWidth = 50;
                    selectedWidth = 154;
                    break;
                case 10:
                    unselectedWidth = 40;
                    selectedWidth = 144;
                    break;
                case 12:
                default:
                    unselectedWidth = 32;
                    selectedWidth = 152;
                    break;
                 case 20:
                    unselectedWidth = 18;
                    selectedWidth = 162;
                    break;
                case 24:
                    unselectedWidth = 15;
                    selectedWidth = 159;
                    break;
                case 29:
                    unselectedWidth = 12;
                    selectedWidth = 168;
                    break;
                case 30:
                    unselectedWidth = 12;
                    selectedWidth = 156;
                    break;
                case 36:
                    unselectedWidth = 10;
                    selectedWidth = 154;
                    break;
                case 48:
                case 60:
                case 72:
                case 96:
                case 120:
                case 132:
                case 144:
                case 150:
                case 156:
                    unselectedWidth = 10;
                    selectedWidth = 154;
                    colorbarWidth = ((unselectedWidth * (count - 1)) + selectedWidth);
                    this.options.colorbar.setStyle('width', colorbarWidth + 'px');
                    break;
            }
            this.options.colorbar.getChildren('li').setStyle('cursor', 'pointer').addClass('unselected').removeClass('selected').set('morph', { 'duration': 0 }).morph({ 'width': unselectedWidth });
            $(cid).setStyle('cursor', 'auto').set('morph', { 'duration': 300, 'oncomplete': $(cid).removeClass('unselected').addClass('selected') }).morph({ 'width': selectedWidth });
        }
    }
});
// make a scrollbar
var makeScrollbar = new Class({
	initialize: function(element, parent) {
		// delete any existing scrollbars
		if ($('hslider')) {
		    $('hslider').removeEvents(); //debug dk 030410:1519
			$('hslider').destroy();
		}
		// first, get the width of the entire element
		// then create the horizontal scrollbar
		var scrollSize = element.getSize();
		// only create the scrollbar if required
		var difference = scrollSize.x-504;
		if (difference > 0) {
			// create the scrollbar track
			var scrollbar = new Element('div', {
				'id': 'hslider'
			}).inject(element.getParent(), 'top');
			// create the knob
			var scrollknob = new Element('div', {
				'id': 'hknob'
			}).inject(scrollbar);
			var slider = new Slider($('hslider'), $('hknob'), {
				steps: difference,
				wheel: 'true',
				onChange: function(step){
					element.setStyle('left', -step);
				}
			}).set(0);
			// Scroll the content element when the mousewheel is used within the
			// content or the scrollbar element.
			$$(element, $('hslider')).addEvent('mousewheel', function(e) {
				e = new Event(e).stop();
				var step = slider.step - e.wheel * 30;
				slider.set(step);
			});
			// Stops the handle dragging process when the mouse leaves the document body.
			$(document.body).addEvent('mouseleave', function() { slider.drag.stop() });
		}
	}
}); // end class makeScrollbar

// JIT validation on forms. Not strictly necessary. Can cause problems in IE6.
var updateProfileFormValidator = new Class({
	initialize: function(){
		new Form.Validator.Inline($('updateProfileForm'), {
			stopOnFailure: true,
			useTitles: true,
			errorPrefix: "",
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					form.submit();
				}
			}
		});
	}
});

var changePasswordFormValidator = new Class({
	initialize: function(){
		new Form.Validator.Inline($('changePasswordForm'), {
			stopOnFailure: true,
			useTitles: true,
			errorPrefix: "",
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					form.submit();
				}
			}
		});
	}
});

var shareFormValidator = new Class({
	initialize: function(){
		new Form.Validator.Inline($('shareForm'), {
			stopOnFailure: true,
			useTitles: true,
			errorPrefix: "",
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					form.submit();
				}
			}
		});
	}
});

var uploadFormValidator = new Class({
	initialize: function(){
		new Form.Validator.Inline($('uploadForm'), {
			stopOnFailure: true,
			useTitles: true,
			errorPrefix: "",
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					form.submit();
				}
			}
		});
	}
});

// custom validators
FormValidator.add('validate-zipCode', {
   errorMsg: 'Please enter a valid ZIP code. For example &quot;12345&quot; or &quot;12345-6789&quot;.',
   test: function(element, props) {
      return (/^[\d]{5}(-[\d]{4})?$/).test(element.get('value'));
   }
});

// colorPicker results Popups
var colorPickerResultsPopups = new Class({
	Implements: [Options, Events],
	options: {
		container: 'colorPickerResults',
		explore: '.explore',
		productResult: '.productResult'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.container = $(this.options.container);
		this.explore = $$(this.options.explore);
		this.productResult = $$(this.options.productResult);
		
		//if ($chk(this.container)) {
		//	this.attachExploreEvents();
		//}
	},
	attachExploreEvents: function() {
		//console.log('in attachExploreEvents');
		// reinitialize element collections for new elements built by productResultsReq.buildResults()
		this.productResult = $$(this.options.productResult);
		this.explore = $$(this.options.explore);

		this.productResult.each( function(el) {
			var handle = el.getFirst('.ctrlExplore');
			var handlePos = handle.getCoordinates();
			var exploreIdx = el.getProperty('id');
			// pull id number
			exploreIdx = exploreIdx.substr(exploreIdx.indexOf('_')+1);
			handle.setStyle('cursor', 'pointer');
			handle.addEvent('click', function(e) {
				this.showExplorePopup(exploreIdx, handlePos.left - 150, handlePos.top);
			}.bind(this));
		}, this);
	},
	showExplorePopup: function(idx, xPos, yPos) {
		this.hideAllPopups();
		var exploreBox = $('explore_'+idx);
		exploreBox.setStyle('display', 'block');
		var exploreBoxSize = exploreBox.getSize();
		var exploreBoxCloseHandle = exploreBox.getFirst('.btnClose');
		
		exploreBoxCloseHandle.addEvent('click', function(e) {
			e.stop();
			this.hideAllPopups();
		}.bind(this));
		
		exploreBox.setStyles({
			height: exploreBoxSize.y,
			left: xPos,
			top: yPos - exploreBoxSize.y
		});
		//exploreBox.setStyle('display', 'block');
	},
	hideAllPopups: function() {
		this.explore.each( function(el) { 
			//el.addClass('exploreHidden');
			el.setStyle('display', 'none');
		});
	},
	destroyAllResults: function() {
		//console.log('destroying old results');
		$$('.btnClose').each( function(el) { el.removeEvents(); });
		$$('.ctrlExplore').each( function(el) { el.removeEvents(); });
		this.explore.each( function(el) { el.destroy(); });
		this.productResult.each( function(el) { el.destroy(); });
	}
});


// colorPicker event/result/AJAX/JSON handlers
// polls form fields and map sliders for changes, waits for values to settle, then makes AJAX call
var colorPickerProductResultsReq = new Class({
	Implements: [Options, Events],
	options: {
		resultsContainer: 'colorPickerResults',
		exploreContainer: 'all',
		fieldR: 'cp1_Red',
		fieldG: 'cp1_Green',
		fieldB: 'cp1_Blue',
		//inputs: '.userInput'
		resultPrompt: 'resultPrompt',
		blankImageSrc: '/Style Library/PrismaColor/scripts/colorpicker/img/blank.png'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.resultsContainer = $(this.options.resultsContainer);
		this.exploreContainer = $(this.options.exploreContainer);
		//this.inputs = $$(this.options.inputs);
		this.fieldR = $(this.options.fieldR);
		this.fieldG = $(this.options.fieldG);
		this.fieldB = $(this.options.fieldB);
		this.data = Array();
		this.resultPrompt = $(this.options.resultPrompt);
	},
	/*
	checkUserInputs : function() {
		this.inputs.each( function(el) {
			el.addEvent('change', function(e) {
				console.log('changed');
				this.makeRequest();
			}.bind(this));
		}, this);
	},
	*/
	makeRequest: function() {
		//console.log('r: ', this.fieldR.value, ' g: ', this.fieldG.value, ' b: ', this.fieldB.value);
		//var jsonURL = './json/closest-color-sample.json';
	//var jsonURL = 'http://spdev-draftfcb.com/_layouts/Prisma/Pages/PrismaClosetColorService.aspx'
	var jsonURL = $('colorPickerServiceUrl').getElements('input[name$=hdnColorPickerFeedUrl]')[0].value;
		var fragment = 'r='+this.fieldR.value+'&g='+this.fieldG.value+'&b='+this.fieldB.value;
		new Request.JSON({
			url: jsonURL,
			method: 'get',
			onRequest: function() {
				//console.log('req made');
				//console.log('fragment: ', fragment);
			}.bind(this),
			onSuccess: function(jsonObj, text) {
				//console.log('json obj: ', jsonObj);
				//console.log('req success');
				if (jsonObj) {
					this.data = jsonObj;
					this.buildResults('success');
				} else {
					this.buildResults('no matches');
				}
			}.bind(this),
			onFailure: function() {
				//console.log('req failed');
				this.buildResults('failed');
			},
			onException: function() {
				//console.log('req exception');
				this.buildResults('exception');
			}
		}).send(fragment);
	},
	buildResults: function(reqResponse) {
		// get rid of old results
		resultsPopups.destroyAllResults();
		
		var numResults = this.data.length;
		
		switch (reqResponse) {
			case 'success':	
				this.resultPrompt.innerHTML = numResults + ' Prismacolor products are&nbsp;available:';
				this.resultPrompt.setStyle('border-bottom', '1px solid #c9cac6');
				
				for (var i = 0; i < numResults; i++) {
					var isAvailIndiv = '';
					var isAvailIndivExplore = '';
					if (this.data[i].isAvailableIndividually) {
						isAvailIndiv = 'This color is also available individually.';
						isAvailIndivExplore = 'individually or ';
					}
					
					var colorSetsCopy = '';
					var colorSetsCopyExplore = '';
					var colorSets = new Array();
					if (this.data[i].colorsets) {
						// match only contiguous digits, i.e. set numbers
						colorSets = this.data[i].colorsets.match(/\d+/g);
						//console.log('colorsets: ', this.data[i].colorsets);
						//console.log('matched: ', colorSets);
						
						// turn array of set numbers into English, no Oxford comma
						if (colorSets.length > 0) {
							colorSetsCopy = this.data[i].name + ' is available in the following sets: ';
							colorSetsCopyExplore = 'in sets of ';
							if (colorSets.length > 2) {
								for (var j = 0; j < colorSets.length - 2; j++) {
									colorSetsCopy = colorSetsCopy + colorSets[j] + ', ';
									colorSetsCopyExplore += colorSets[j] + ', ';
								}
								colorSetsCopy += colorSets[colorSets.length-2] + ' &amp; ' + colorSets[colorSets.length-1];
								colorSetsCopyExplore += colorSets[colorSets.length-2] + ' &amp; ' + colorSets[colorSets.length-1];
							} else if (colorSets.length == 2) {
								colorSetsCopy += colorSets[0] + ' &amp;&nbsp;' + colorSets[1];
								colorSetsCopyExplore += colorSets[0] + ' &amp;&nbsp;' + colorSets[1];
							} else {
								colorSetsCopy += colorSets[0];
								colorSetsCopyExplore += colorSets[0];
							}
						}
					}
					
					// display Premier headline if product is a Premier product
				    var headlinePremier = '';
                    if (this.data[i].productname.contains('Premier'))
                    {    headlinePremier = '<h2 class="headlinePremier"><span class="skipnav">Premier</span></h2>';}
                    else if (this.data[i].productname.contains('Scholar'))
                        headlinePremier = '<h2 class="headlineScholar"><span class="skipnav">Scholar</span></h2>';
					
				    var pColorId = '';
                    if (this.data[i].id != null)
                    { pColorId = ' | ' + this.data[i].id }
			
					var resultHtml =	'<div class="colorPreview" style="background-color:rgb('+this.data[i].rgb+');"></div>'+headlinePremier+'<h2 class="ctrlExplore">'+this.data[i].productname+'</h2><p>'+colorSetsCopy+'. '+isAvailIndiv+'</p><p class="productCodes">'+this.data[i].name + pColorId;
					
					var exploreHtml = '<div class="exploreTop"></div><div class="exploreBody"><img class="exploreProdImg" src="'+this.data[i].productimage+'" width="139" height="139" alt=""><a class="btnExplore" href="'+this.data[i].productlink+'"><span class="skipnav">Explore this product</span></a>'+headlinePremier+'<h2>'+this.data[i].productname+'</h2><h3>About this product:</h3><p>'+this.data[i].desciption+' Sold '+isAvailIndivExplore+colorSetsCopyExplore+'.</p><div class="spacer"></div></div><div class="exploreBottom"></div><a class="btnClose"><span class="skipnav">Close</span></a>';
					
					var resultDiv = new Element('div', {
						'class': 'productResult',
						'id': 'productResult_'+i,
						'html': resultHtml
					}).inject(this.resultsContainer, 'bottom');
					
					var exploreDiv = new Element('div', {
						'class': 'explore',
						'id': 'explore_'+i,
						'html': exploreHtml
					}).inject(this.exploreContainer, 'bottom');
				}
				// if IE6 then apply alpha filter to injected png images
				var IEversion = parseFloat(navigator.appVersion.split("MSIE")[1]);
				if ((IEversion < 7) && (document.body.filters)) {
				//if (Browser.Engine.trident && (Browser.Engine.version < 7)) {
					var pnglist = $$('.exploreProdImg');
					pnglist.each( function(el) {
						if (el.getProperty('src').match(/\.PNG|\.png$/)) {
							el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + el.getProperty('src') + '\', sizingMethod=\'scale\');';
							el.src = this.options.blankImageSrc;
						}
					}, this);
				}
				resultsPopups.attachExploreEvents();
				break;
			case 'no matches':
				this.resultPrompt.innerHTML = 'No matches found.';
				break;
			case 'failed':
			case 'exception':
			default:
				this.resultPrompt.innerHTML = 'There has been an error.';
				break;
		}
	}
});

window.addEvents({
	'domready': function(){									 
		new HTML5();
		
		if ($('paletteHelperContainer') != null) {
            var paletteExist = $('paletteHelperContainer').getElements('input[name$=hdnPaletteExist]')[0].value;
            if (paletteExist == "true") {
                new detailsBox();
                new paletteChooser();
            }
        }
		new slideshow();
		if ($chk($('artistCarousel'))) { new artistCarousel(); }

	if ($chk($('artistTabs'))) { new artistTabs(); }
		if ($chk($('webform'))) { new studioFormDynamics(); }
		if ($chk($('updateProfileForm'))) { new updateProfileFormValidator(); }
		if ($chk($('changePasswordForm'))) { new changePasswordFormValidator();	}
		if ($chk($('shareForm'))) { new shareFormValidator(); }
		if ($chk($('uploadForm'))) { new uploadFormValidator(); }
		
		if ($chk($('colorPicker'))) {
			cp1 = new ColorPicker('cp1',{startHex: 'ffcc00', startMode:'s'}); 
			resultsPopups = new colorPickerResultsPopups();
			productResultsReq = new colorPickerProductResultsReq();
		}
    $('all').getElement('footer').setStyle('display', 'none');
	$('all').getElement('footer').setStyle('display', 'block');
	},
	'resize': function(){
	}
}); // end domready function
