/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */

if (!window.log) {
	/**
	 * Debug convenience function
	 * @param {String} msg
	 */
	function log(msg) {
		if(typeof window.console === 'object') {
			console.log(msg);
		} else {
			return;
		}
	}
}

if (!window.d) {
	/**
	 * Debug convenience function
	 * @param {String} msg
	 */
	function d(msg) {
		var cilDebug = cil && cil.app && cil.app.debug;
		var globalDebug = window.debug || window.log;
		if (globalDebug || cilDebug) {
			log(msg);
		}
	}
}


(function($) {
	
	// static constructs
	var cil = window.cil = window.cil || {};

	/*
	 * cil.color
	 *
	 * !!!
	 * !!!  This must always come first!
	 * !!!
	 * 
	 * Stores CIL Color information 
	 *
	 * cil.color.build(el,mood) 			// Build color chips
	 * cil.color.load(data);				// Load Color Data
	 * cil.color.get('0142');				// Returns color object
	 * cil.color.getAll('mood');			// An indexed hash of color objects (in this case, mood index)
	 * cil.color.getAll('mood','1');		// All colored objects for this mood index
	 * cil.color.getAll('chip','011');		// All colored objects for this chip index
	 */
	
	cil.color = {
		version: '0.9',
		conf: {
			lang: 'en',
			blankColor: {
				cilKeyId: 'blank',
				hex: '#DDDDDD',
				hexAlt: '#999999',
				name: ( location.href.indexOf("/fr/") > 1 ) ? "Faites glisser une couleur ici." : "Drag a color here.",
				moodId: false,
				familyId: false
			}
		}
	};
	
	$.extend(cil.color,(function() {
		
		var self = {};
		
		self.data = self.data || {};
		
		self.indexes = self.indexes || {};
		
		function __pad(number, length) {
			var str = '' + number;
			while (str.length < length) {
				str = '0' + str;
			}
			return str;
		}
		
		return {
			padKey: function(cilKey) {
				return __pad(cilKey || 0000,4);
			},
			buildColors: function(colorEl, mood) {
				
				var colorData = false, colorKeys = [], i = 0, colEl = false;
			
				if (!colorEl || !mood) { return false; }
				
				colorEl.empty();
		
				colorData = self.getAll('mood',mood);
				
				if (!colorData) {
					d('Color data unavailable.');
					return false;
				}
				
				colorKeys = [];
				
				for (var cilKey in colorData) {
					if (1===1) { // JSLint Safety measure
						colorKeys.push(cilKey);
					}
				}
			
				i = 1;
				colEl = $('<div class="col" />');
				
				for (var key in colorData) {
					if (typeof key === 'object' || key === 'name' || key === 'moodId') { continue; }
					var c = colorData[key];
					var swatchEl = $('<div class="' + $.cil.swatch.conf.swatchClass.substr(1) + '" style="background:'+c.hex+';" data-cil-key="'+c.cilKey+'">&nbsp;</div>');
					colEl.append(swatchEl);
					if (i === 6) {
						i = 0;
						colorEl.append(colEl);
						colEl = $('<div class="col" />');
					}
					i++;
				}
				return colorEl;
		
			},
			get: function(a,b) {
				var index = b ? a : 'color';
				var key = b ? b : a;
				return self.data[index] ? self.data[index][key] : undefined;
			},
			getAll: function(a,b) {
				if ((!a && !b) || a === 'color') { return self.data.color; }
				if (!self.indexes[a]) { return undefined; }
				return b ? self.indexes[a][b] : self.indexes[a];
			},
			getBlankColor: function() {
				return cil.color.conf.blankColor;
			},
			load: function(data) {
				
				var color = data.color;
			
				delete(data.color); // Remove because we'll rebuild in the loop a little farther down
				
				self.data = data; // Other data (mood, family, chip) comes ready
				
				// Build index place holders
				$.each('mood,family,chip'.split(','), function(i, indexName) {
					self.indexes[indexName] = {};
					var key = indexName+'Id';
					$.each(self.data[indexName],function(j,indexData) {
						var indexable = indexData[key];
						self.indexes[indexName][indexable] = {};
					});
				});
								
				// Place holder for color data
				self.data.color = {};
				
				for (var i = color.length; i--; ) {

					var key = color[i].k;
					var moodId = color[i].m_id;
					var familyId = color[i].f_id;
					var chipId = color[i].c_id;
					
					self.data.color[key] = {
						cilKey      : color[i].k,
						cilClass    : 's'+color[i].k,
						hex         : color[i].h,
						hexAlt      : color[i].h2,
						name        : color[i].name,
						moodId      : color[i].m_id,
						familyId    : color[i].f_id,
						chipId		: color[i].c_id,
						chipPos		: color[i].p
					};

					// Set color and create indexed data 
					self.indexes.mood[moodId][key] = self.indexes.family[familyId][key] = self.indexes.chip[chipId][key] = self.data.color[key];
				
				}
			
			}
		};
	})());


	/*
	 * cil.app
	 *
	 * cil.app.initMyPalette();			// Initialize Quick Palette, My Palette, and History Palette
	 * cil.app.initGallery();			// Initialize Gallery and Gallery Palette
	 * cil.app.getPaletteApi();			// Return a particular cil.app palette
	 * 
	 */

	cil.app = {
		version: '0.9',
		conf: {
			baseUrl: 'http://www.cil.ca',
			els: {
				q: {
					p: '#quickSwatch',
					s1: '#quick-swatch-1',
					s2: '#quick-swatch-2',
					s3: '#quick-swatch-3'
				},
				m: {
					p: '#mySwatch',
					s1: '#cil-swatch-1',
					s2: '#cil-swatch-2',
					s3: '#cil-swatch-3',
					s4: '#cil-swatch-4'
				},
				h: {
					p: '#myHistory',		// History Palette
					w: '.wrap-swatch'		// Wrapper for History's swatches
				},
				c: {
					p: '.CIL_Colors'
				},
				g: {
					p: '#gallerySwatch',
					s1: '#gallery-swatch-1',
					s2: '#gallery-swatch-2',
					s3: '#gallery-swatch-3',
					g : '#CIL_Gallery',
					t : '#CIL_Thumbs',
					u : '.prevPage',
					d : '.nextPage',
					l : '.prevImg',
					r : '.nextImg'
				}
			}
		}
	};

	$.extend(cil.app,(function() {
		
		var self = {}, loaded = false;
		
		// Palette and Known Swatch Selectors
		var o = cil.app.conf.els;
	
		cil.color.load(cil.rawColors);
	
		// Pallete APIs
		self.qApi = null; // Quick API
		self.mApi = null; // MySwatches API
		self.hApi = null; // History API
		
		function __pad(number, length) {
			var str = '' + number;
			while (str.length < length) {
				str = '0' + str;
			}
			return str;
		}
		
		return {
			buildLink: function(prefix,suffix) {
				var url_part = ( location.href.indexOf("/fr/") > 1 ) ? '/fr/my-swatch/palette/' : '/my-swatch/palette/';
                var url = cil.app.conf.baseUrl + url_part;
				var s1 = $(o.q.s1).swatch().colorData.cilKey;
				var s2 = $(o.q.s2).swatch().colorData.cilKey;
				var s3 = $(o.q.s3).swatch().colorData.cilKey;
				return url + cil.color.padKey(s1) + cil.color.padKey(s2) + cil.color.padKey(s3) + '/';
			},
			buildSwatchQTips: function (swatches,qTipOpts,x) {
				var defaultTipConf = $.cil.qtip.conf;
				// Speed Optimizations
				for (var i = swatches.length; i--; ) {
					var el = $(swatches[i]);
					var colorData = cil.color.get(el.attr('data-cil-key')) || false;
					var tipConf = qTipOpts ? $.extend(defaultTipConf, qTipOpts): defaultTipConf;
					tipConf.content = '<div class="CIL_Swatch" style="background:'+ colorData.hex +'"><span style="color:'+ colorData.hexAlt +'">' + colorData.name + '</span></div>';
					el.qtip(tipConf);
					el.unbind('click').click(function(e) {

						//d('Palette item clicked');
						
						var dropColorData, swatchEl;
						
						//cil.myPalette.stopItemAnims(); // Stop animating items
						
						$(o.q.p).click(); // Open window
						
						dropColorData = $(e.currentTarget).swatch({api:true}).colorData;
						
						swatchEl = cil.myPalette.existingItem(dropColorData, true, true) || cil.myPalette.addItem(dropColorData);
						
						$(swatchEl).effect("pulsate", { times:4 }, 550);
						
					});
				}
			},
			updateTable: function() {
				$.each($('.CIL_Table').find('.wrap-swatch'), function(i, wrapEl) {
					wrapEl = $(wrapEl);
					var src = $(wrapEl.attr('rel'));
					var color = src.swatch().colorData;
					wrapEl.find('.CIL_Swatch').swatch({api:true}).render(color);
					if (color.cilKeyId !== 'blank') {
						wrapEl.find('.name').text(color.name);
						wrapEl.find('.mood').text(cil.color.get('mood',color.moodId).name).attr('href',cil.app.conf.baseUrl + '/gallery?galleryId='+color.moodId);
						wrapEl.find('.chip').text(color.chipId);	
					}
				});
			},
			updateMyPalette: function() {
				$.each($(o.m.p).find('.CIL_Swatch'), function(i, el) {
					el = $(el);
					var srcEl = $(el.attr('rel'));
					var srcColor = srcEl.swatch({api:true}).colorData;
					el.swatch({api:true}).render(srcColor);
				});
			},
			manualUpdate: function(a,b,c) {
				function updateSwatch(id, color) {
					if (!id || !color) { return; }
					$(id).swatch({api:true}).render(color);
				}
				if (a) { updateSwatch('#quick-swatch-1',a);	}
				if (b) { updateSwatch('#quick-swatch-2',b);	}
				if (c) { updateSwatch('#quick-swatch-3',c);	}
				if (a || b || c) {
					cil.app.updateMyPalette();
					cil.app.updateTable();
				}
				return;
			},
			init: function() {
				if (loaded) {
					return;
				}
				self.qApi = $(o.q.p).palette({
					api: true,
					onAfterLoad: function(e) {
						
						var overlayEl = $('.myPaletteOverlay');
						var inlineEl = $('.myPaletteInline');
						
						if(inlineEl.length >= 1) {
							overlayEl.remove();
							overlayEl = false;
							cil.color.conf.blankColor.name = ( location.href.indexOf("/fr/") > 1 ) ? 'No de couleur' : 'No color selected';
							cil.app.updateTable();
						}
						
						if (overlayEl && overlayEl.length >= 1) {

							$(o.q.p).overlay($.extend($.cil.overlay.conf, {
								onBeforeLoad: function() {
									
									//alert($(o.m.s1).attr('id') + ' ' + $(o.m.s1).attr('class'));
									$(o.m.s1).swatch().render($(o.q.s1)); // REmoved tyler
									$(o.m.s2).swatch().render($(o.q.s2));
									$(o.m.s3).swatch().render($(o.q.s3));
									
								}
							}));
						}
						
					},
					swatchConf: {
						cookie: true,
						autoRender:true
					}
				});

				cil.myPalette.init();
				cil.gallery.init();
				cil.app.buildSwatchQTips($(o.c.p).find('.CIL_Swatch'));
				loaded = true;
			}
		};
	})());
	
	

	
	/*
	 * cil.flash
	 *
	 * Provides methods for disperate Flash functions:
	 * - Automatic application of sIFR
	 * - JavaScript routing for mood videos
	 * - JavaScript embedding
	 *
	 * cil.flash.redirectTo('projects'); 		// Redirects to project page
	 * cil.flash.redirectTo('yahoo');			// Redirects to Yahoo!
	 * cil.flash.videoComplete();				// Some action occurs
	 */
	
	cil.flash = {
		version: '0.9',
		conf: {
			rooms: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/gallery/deep_and_luxurious' : '/gallery/deep_and_luxurious',
			projects: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/project/' : '/project/',
			schemes: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/ideas/colour-coordinator/' : '/ideas/colour-coordinator/',
			deepAndLuxurious: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/ideas/collection/deep-luxurious.html' : '/ideas/collection/deep-luxurious.html',
			cleanAndPlayful: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/ideas/collection/clean-playful.html' : '/ideas/collection/clean-playful.html',
			mellowAndComforting: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/mellow-comforting/' : '/mellow-comforting/',
			softAndElegant: ( location.href.indexOf("/fr/") > 1 ) ? '/fr/ideas/collection/soft-elegant.html' : '/ideas/collection/soft-elegant.html'
		}
	}; 
	
	$.extend(cil.flash,(function() {

		// Apply sIFR methods on startup
		var cosiva = { src: '/w/l/sifr/fonts/cosiva.swf' };
		sIFR.activate( cosiva );
		sIFR.replace(cosiva, {
		  selector: 'h1#page-title',
		  css: '.sIFR-root { background-color: #ffffff; color: #555555; }',
		  wmode: 'transparent'
		});
		
		// Public Methods
		return {
			redirectTo: function(action) {
				action = cil.flash.conf[action];
				if (action) {
					window.location = action;
				}
			},
			videoComplete: function() {
				onPageAfterVideo();
                //if( window && window.onPageAction ) {
				//	onPageAfterVideo();
				//}
			},
			embedFlash: function(el, swf) {
				var toggleable = false, userIp = false, devIp = '69.159.202.146';
				function __embedFlash(el,swf,width,height) {
					width = width || $(el).width() || 340;
					height = height || $(el).height() || 220;
					return $(el).flashembed( { src: swf, wmode: 'opaque'} );
				}
				
				if (!toggleable) {
					return __embedFlash(el,swf);
				}
				
				$.getJSON("http://jsonip.appspot.com?callback=?", function(data){
					userIp = data.ip;
					if (toggleable && (userIp === devIp) ) {
						var link = $('<p align="center"><span>Load Flash<br />'+swf+'</span></p>').click(function(){__embedFlash(el,swf);});
						$(el).html(link);
					} else {
						__embedFlash(el,swf);
					}
				});
				
			}
		};
	})());
	
	
	/*
	 * cil.gallery
	 *
	 * Creates the CIL Photo & Color Gallery. Uses jQuery tools scrollable,
	 * plus the swatch and palette classes
	 *
	 * cil.gallery.init();						// Starts everything
	 */
	
	cil.gallery = {
		version: '0.9',
		conf: {
			nextPage: '.nextPage',
			prevPage: '.prevPage',
			nextItem: '.nextItem',
			prevItem: '.prevItem'
		}
	};
	
	$.extend(cil.gallery,(function() {

		var self = {};
		
		// Palette and Known Swatch Selectors
		var o = cil.app.conf.els;

		
		return {
			
			init: function() {
				
				// Build QTIPs
				// Setup elements
				var gEl = $(o.g.g);
				var tEl = $(o.g.t);
				var pEl = $(o.g.p);
				
				var api = $(o.g.t).scrollable({
					vertical:true,
					loop: true,
					size: 3
				}).circular().mousewheel({api: true});
				
				var gApi = pEl.palette({
					api:true,
					swatchConf: {
						cookie: false
					}
				});
				
				// Swatches created by the palette
				var s1 = $(o.g.s1);
				var s2 = $(o.g.s2);
				var s3 = $(o.g.s3);

				// Gallery Palette contains a quickLoading link
				pEl.click(function() {
					var gSwatches = pEl.find('.CIL_Swatch');
					cil.myPalette.bulkAddItems(gSwatches);
					$(o.q.p).click();
				});
				
				// Gallery Image
				var galleryImg = $('#CIL_Photo');
				var bufferImg = $('#CIL_Buffer');
				
				// Left and right buttons -- Move Gallery forwards and backwards a step
				var rightBtn = gEl.find(o.g.r);
				var leftBtn = gEl.find(o.g.l);
				
				
				$(".items img").click(function() {
					
					var thumbEl = $(this);
					
					
					var curUrl = galleryImg.attr('src');
					var url = thumbEl.attr("highres");
					
					if ( curUrl === url ) {
						return this;
					}
					
					// recursive rendering function to animate sequential changes
					var animateChange = function(el,key,f) {
						var cilKey = thumbEl.attr(key);
						return function() { // Return a function 
							el.animate(
								{ backgroundColor: cil.color.get(cilKey).hex }, // Animate to the new background color (pulled from cil.color)
								150,
								null,
								(el.swatch().render(cilKey) && f) // Callback Coolness: Automatically render new swatch and use x&&y trick to execute both statements while returning the latter's value 
							);
						}
					}					
					
					// Everything except getting the right url occurs
					// after we've loaded the image. Speeds things up.
					// Also, note the one('click') binding of the left
					// and right buttons. Prevents extra clicks
					// while the image loads...
					
					//galleryImg.stop().fadeTo('fast', 0.5, function() {
					galleryImg.stop().fadeTo('fast', 0, function() {
						var imgBuffer = new Image();
						imgBuffer.onload = function() {
							galleryImg.attr('src', url).fadeTo('slow',1, function() {
							
								// Bind the Left once
								rightBtn.one('click',function(e){
									tEl.find('.active').next().click();
									return false;
								});
								
								// Bind the right once
								leftBtn.one('click',function(e){
									tEl.find('.active').prev().click();
									return false;
								});
								
							});
							
							
							/*
							 * Swatches are rendered with a stupidly recursive function
							 * required to perfrom sequential animations... 
							 */
							animateChange(s3,'data-cil-key-3',
								animateChange(s2,'data-cil-key-2',
									animateChange(s1,'data-cil-key-1', function() {
										
										var qTipEls= $(o.g.p).find('.CIL_Swatch');
									
										$.each(qTipEls, function(i,el) {
											el = $(el);
											el.data('qtip') ? el.qtip("destroy") : false ;
										});
										
										cil.app.buildSwatchQTips(qTipEls, {
											position: {
												corner: { target:'rightMiddle', tooltip: 'leftMiddle'}
											}
										},true);
										
									}) 
								)
							)(); // And start recursion
							
						}
						
						imgBuffer.src = url; // LEAVE IN!! Start buffering in the image
			
					}).css({opacity:1});
					
			
				}).filter(":first").click();
				
			}
		};

	})()); // end cil.app.gallery

	/*
	 * cil.myPalette
	 *
	 * Stores user's selected palette information
	 */
	cil.myPalette = {
		version: '1.1',
		conf: {
			dragConf: {
				helper: 'clone',
				revert:true,
				start: function(e, ui) {
					$('.CIL_Swatch:animated').stop().css({opacity: '1'});
					$(ui.helper).css({opacity: '1'});
				},
				zIndex: 1000
			}
		}
	};
	
	$.extend(cil.myPalette,(function() {
		
		var self = {};
		
		// Palette and Known Swatch Selectors
		var o = cil.app.conf.els;
		
		self.hEl = false;
		self.hApi = false;
		self.qApi = false;
		
		return {
			addItem: function (colorData,removeDups) {
				
				if (!colorData || !colorData.cilKey) {
					d('Not creating droppable swatch.');
					return false;
				}
				if (removeDups) {
					cil.myPalette.removeExtraItems();
				}
				
				var textEl = $('<span />').text(colorData.name);
				var dropEl = $('<div class="CIL_Swatch draggable '+colorData.cilClass+'" data-cil-key="'+colorData.cilKey+'">&nbsp;</div>').draggable(cil.myPalette.conf.dragConf);
				var wrapEl = $('<div class="wrap-swatch">&nbsp;</div>').append(dropEl).append(textEl);
				
				self.hEl.prepend(wrapEl);
			
				return wrapEl;
			
			},
			addMessageToBlankSwatches: function(swatchEls, text) {
				$.each(swatchEls, function(i, el) {
					el = $(el);
					var dataAttr = el.attr('data-cil-key');
					if (!dataAttr) {
						el.find('span').text(text);
					}
				});
			},
			bulkAddItems: function (swatches) {
				$.each(swatches, function(i, swatchEl) {
					var colorData = $(swatchEl).swatch({api:true}).colorData;
					swatchEl = cil.myPalette.existingItem(colorData, true, true, true);
					if (!swatchEl) {
						swatchEl = cil.myPalette.addItem(colorData, true);
					}
					swatches = $(swatchEl).find('.CIL_Swatch').andSelf().filter('.CIL_Swatch').effect("pulsate", { times:4 }, 550);
				});
			},
			existingItem: function (colorData,checkSwatchHistory, checkUserPalette,debug) {
				
				var swatches = [];
				
				if(checkSwatchHistory) {
					var historySwatches = $(o.h.p).find('.'+colorData.cilClass+'');
					$.merge(swatches,historySwatches);
				}
				
				if (checkUserPalette) {
					var userSwatches = $(o.m.p).find('.'+colorData.cilClass+'');
					$.merge(swatches,userSwatches);
				}
				
				return swatches.length >= 1 ? swatches : false;
			
			},	
			init: function() {
				
				
										  
				// Make sure we initialize the APIs
				self.hEl = $(o.h.p);
				self.hApi = $(o.h.p).palette({api:true});
				self.qApi = $(o.q.p).palette({api:true});
				
				// Create MyPalette object
				self.mApi = $(o.m.p).palette({
					api: true,
					swatchConf: {
						content: function(colorData) {
							return '<span style="color:' + colorData.hexAlt + ';">' + (colorData.name || '') + '</span>';
						},
						autoRender: true
					}
				});
				
				// Initialize empty swatches
				dragtext = ( location.href.indexOf("/fr/") > 1 ) ? "Faites glisser une couleur ici." : "Drag a color here.";
                cil.myPalette.addMessageToBlankSwatches($('#mySwatch .CIL_Swatch'), dragtext );
				
				// Initialize MyPalette's swatchces when their relevant QuickSwatches
				// have saved cookie values (MyPalette mirrors QuickSwatches)
				$.each($('#mySwatch .CIL_Swatch'), function(i, swatchEl) {
					var sourceEl = $(swatchEl).attr('rel');
					var colorData = $(sourceEl).swatch({api:true}).colorData;
					var api = $(swatchEl).swatch({api:true}).render(colorData);
				});
				
				// Create History palette for use with MyPalette
				self.hApi = $(o.h.p).palette({api:true});
			
			
				$('.draggable').draggable(cil.myPalette.conf.dragConf);
				
				var dropTargets = $(o.m.p).find($.cil.swatch.conf.swatchClass).not(o.m.s4);
				
				dropTargets.droppable({
					over: function (event, ui) {
						var dragApi = $(ui.draggable).swatch({api:true});
						var dropApi = $(this).swatch({api:true}).render(dragApi.colorData);
					},
					out: function (event, ui) {
						var dragApi = $(ui.draggable).swatch({api:true});
						var dropApi = $(this).swatch({api:true});
						dropApi.render(dropApi.getLastColor());
					},
					drop: function(event, ui) {
						
						var dropEl = $(this)
						
						// Droppable contains everything we need for color information, and
						//  beacuse it changes on hover to the new one, we pull the
						// existing color from getLastColor() )
						var oldColor = dropEl.swatch({api:true}).getLastColor();
						var newColor = dropEl.swatch({api:true}).getColor();
						
						// Update this element's quick Swatch
						var quickSwatch = $($(this).attr('rel')).swatch();
						quickSwatch.render(newColor);
			
						var existingItems = cil.myPalette.existingItem(newColor, true);
						
						
						if (existingItems) {
							cil.myPalette.removeItem(existingItems); // Remove color swatch from history list
						}
						
						var el = cil.myPalette.addItem(oldColor); // Add new item to the history list
						
						if (el) {
							$(el).hide().slideDown(); // Show that new item
						}
						
						dropEl.stop().css('opacity',1); // Sometimes the droppable is caught midAnimation
					}
				});
			},
			removeExtraItems: function() {
				// Note: We want to have 7 items, but look for anything greater than 5
				// Because when adding items to the history that aren't in the user's palette,
				// We check for extra elements before adding the new one, therefore the list
				// Is one shorter than we imagine
				//$.each($('#myHistory .wrap-swatch:gt(5) .CIL_Swatch:visible'), function(i,swatch) {
				$.each($('#myHistory .wrap-swatch').not('removed').filter(':gt(5)').find('.CIL_Swatch'), function(i,swatch) {
					d('Extra items found ' + $(swatch).swatch({api:true}).colorData.cilKey);
					cil.myPalette.removeItem($(swatch),false);
				});
			},
			removeItem: function (el,animateRemoval) {
				
				if (!el) {
					return;
				}
				
				var anim = (typeof animateRemoval === 'undefined') ? true : animateRemoval;
				
				el = $(el).droppable('destroy');
				if (anim) {
					el.stop().parent().addClass('removed').slideUp(); // Note hiding the swatch element AND the parent wrapper element, making sure you stop other possibly queued animations.. and the removed class
					el.empty();  
				} else {
					el.hide().parent().stop().hide().empty().addClass('removed'); // Note hiding the swatch element AND the parent wrapper element, making sure you stop other possibly queued animations... and the removed class
				}
			
			},
			stopItemAnims: function () {
				$(o.m.p).find('.CIL_Swatch').stop();
				self.hEl.find('.wrap-swatch:visible, .wrap-swatch .CIL_Swatch').stop();
			}
		}
	})());
	
})(jQuery);



(function($){

			
	// static constructs
	$.cil = $.cil || {};
	
	$.cil.palette = {
		version: '2',
		conf: {
			api: false,
			swatchConf: false,			// Declare default conf for Palette's Swatches
			swatchClass: '.CIL_Swatch' 	// Default swatch class
		}
	};
	
	$.cil.swatch = {
		version: '1',
		conf: {
			api: false,
			cilKey: false, 						// CIL Color Key for this swatch
			cookie: false,						// Save element's color into a cookie?
			colorData: false, 					// CIL Color Object
			content: false,
			keyAttr: 'data-cil-key',			// HTML attribute where cil color key is stored
			autoRender: false,					// Is swatch.render() called on Swatch init?
			swatchClass: '.CIL_Swatch',			// Default swatch class
			useImage: false						// Append an <img /> containing the color inside the swatch?
		}
	};
	
	$.cil.qtip = {
		version: '1',
		conf: {		
			content: {
				text: '&nbsp;'
			},
			position: {
				corner: {
				   target: 'topMiddle', // Position the tooltip above the link
				   tooltip: 'bottomMiddle'
				},
				adjust: {
				   screen: true // Keep the tooltip on-screen at all times
				}
			 },
			show: { 
				solo: true // Only show one tooltip at a time
			},
			hide: {
				fixed: true // Make it fixed so it can be hovered over
			},
			style: {
				border: {
				   width: 2,
				   radius: 5
				},
				padding: 0, 
				textAlign: 'center',
				tip: true, // Give it a speech bubble tip with automatic corner detection
				name: 'light' // Style it according to the preset 'cream' style
			 }
		 }
	};
	 
	$.cil.overlay = {
		version: '1',
		conf: {
			api:true,
			expose: { 
				color: '#333', 
				loadSpeed: 200, 
				opacity: 0.9 
			}
		}
	};
	
	function Palette(els, conf) {
		
		var self = this, $self = $(this);
		els.data("palette", self); // store a reference to the Palette object... 

		// bind all callbacks from configuration
		$.each(conf, function(name, fn) {
			if ($.isFunction(fn)) { $self.bind(name, fn); }
		});

		// public methods
		$.extend(this, {
			bind: function(name, fn) {
				$self.bind(name, fn);
				return self;  
			},  
			unbind: function(name) {
				$self.unbind(name);
				return self;  
			}
		});
		
		// Trigger our custom onBeforeLoad event
		var e = $.Event();
		e.type = "onBeforeLoad";
		$self.trigger(e);
		
		conf.swatchConf = conf.swatchConf || {};
		
		// Instantiate Swatches
		if (typeof conf.swatches === 'object') {
			jQuery.each(conf.swatches, function(swatchId, swatchConf) {
				$(swatchId).swatch($.extend(conf.swatchConf, swatchConf));
			});
			
		} else {
			$.each(els.find(conf.swatchClass),function(i,swatchId) {
				$(swatchId).swatch(conf.swatchConf);
			});
		}
	
		// Trigger our custom onAfterLoad
		e = $.Event();
		e.type = "onAfterLoad";
		$self.trigger(e);
		
	} // e.f.Palette
	
	function Swatch(els, conf) {

		var self = this, $self = $(this);

		self.lastColorData = self.colorData = cil.color.getBlankColor();

		conf = conf || {};
		
		els.data("swatch", self); // store a reference to the Swatch object...

		// bind all callbacks from configuration
		$.each(conf, function(name, fn) {
			if (typeof fn === 'function') { $self.bind(name, fn); }
		});
		
		// check cil.color table 
		function __lookupColor(c) {
			return (typeof c === 'object' && c.cilKey) ? cil.color.get(c.cilKey) : cil.color.get(c) ;
		}
		
		// public methods
		$.extend(this, {
			getColor: function() {
				return self.colorData;
			},
			getLastColor: function() {
				return self.lastColorData;
			},
			getCilKey: function() {
				return self.colorData.cilKey;
			},
			setColor: function(color) {
				
				// Is this an element with HTML5's data attribute? (i.e., data-cil-key)
				if (!color) {
					color =  $(color).attr(conf.keyAttr);
				}
				
				// Is it a colorData object?
				if (color && typeof color === 'object' && color.cilKey) {
					color = color.cilKey;
				}
				
				// Is this a CIL Key?
				if (color && typeof color === 'string' ) {
					color = color;
				}
				
				// Try and fetch a color
				var colorData = cil.color.get(color) || cil.color.getBlankColor();
				
				// Abort -- we can't get new color information
				if (!colorData || !colorData.cilKey) {
					return self;
				}
				
				// Store current color
				self.lastColorData = self.colorData;
				
				// Get new color
				self.colorData = colorData //__lookupColor(color) || cil.color.getBlankColor();
				
				var oldColor  = self.lastColorData;
				var newColor  = self.colorData;
				
				if (oldColor.cilKey === newColor.cilKey) {
					return self;
				}

				//d('Setting CIL color key ' + colorData.cilKey);
				return self;
			
			},
			render: function(colorData) {
				
				if (colorData) {
					self.setColor(colorData);
				}
				
				var newColor = self.colorData;
				var oldColor = self.lastColorData;
				
				if (conf.cookie) {
					$.cookie(els.attr('id'), newColor.cilKey, { path: '/' });
					//d('Updating cookie ' + els.attr('id') + ' to ' + newColor.cilKey);
				}
				
				// Update Swatch class and HTML 5 data attribute (data-cil-key)
				els.addClass(newColor.cilClass).attr(conf.keyAttr,newColor.cilKey);
				
				// Remove existing swatch style
				if(oldColor.cilClass) {
					els.removeClass(oldColor.cilClass)
				}

				// Update Content
				if(self.content) {
					els.find('span').text(newColor.name).css({color:newColor.hexAlt}); // update container
				}
				
				// Update Innner Content
				if (conf.content) {
					// Draw the HTML element and use innerHTML for speed
					els[0].innerHTML = ((typeof conf.content === 'function') ? conf.content(newColor) : conf.content);
				}
				
				// Update Image
				if (conf.useImage) {
					var src = '/w/i/c/'+ newColor.cilKey+'.gif';
					var colorEl = els.find('CIL_Color');
					if (els.length === 0) {
						els.prepend('<img class="CIL_Color" src="' + src + '" />');	
					} else {
						colorEl.attr('src', src);
					}
				}
				
				//d('Rendering '+ els.attr('id') +' (cilKey: '+self.colorData.cilKey+')'); // Debug
				return self;
			},
			bind: function(name, fn) {
				els.bind(name, fn);
				return self;  
			},  
			unbind: function(name) {
				els.unbind(name);
				return self;  
			}
		});

		// Swatches can save their color values into a cookie
		// This requires the element have an explicit ID.
		if (conf.cookie && els.attr('id')) {
			conf.cilKey = $.cookie(els.attr('id')) || conf.cilKey;
		}
		
		// Set the color
		self.setColor(els.attr(conf.keyAttr) || conf.cilKey);

		// Skip autoRendered swatch elements
		if (conf.autoRender) {
			self.render();
		}
		
	} // e.f.Swatch
	
	/*
	 * jQuery Plugin Implementations
	 *
	 * These functions register the objects with jQuery plugin system
	 *
	*/
	
	
	// palette implementation
	$.fn.palette = function(conf) {
		
		var el = this.eq(typeof conf === 'number' ? conf : 0).data("palette");
		if (el) { return el; }
		
		var globals = $.extend({}, $.cil.palette.conf);
		conf = $.extend(globals, conf);		

		// construct exposes
		this.each(function() {
			el = new Palette($(this), conf);
			$(this).data("palette", el);	 
		});		
		
		return conf.api ? el: this;		
	};
	

	// swatch implementation
	$.fn.swatch = function(conf) {

		var el = this.eq(typeof conf === 'number' ? conf : 0).data("swatch");
		if (el) { return el; }

		if (typeof conf === 'string') {
			conf = {cilKey: conf};
		}
		
		var globals = $.extend({}, $.cil.swatch.conf);
		conf = $.extend(globals, conf);		

		// construct exposes
		this.each(function() {
			el = new Swatch($(this), conf);
			$(this).data("swatch", el);	 
		});		
		
		return conf.api ? el: this;		
	};	

})(jQuery);
