/* -------------------------------------------------------------- 
application.js
by Nobleskine from AREA 17

Version date: 6 Oct 2009
Version 0.1 Alpha

Runs at bottom of the page
-------------------------------------------------------------- */

animating = false;

$(document).ready(function(){
	runOnDOMready();
});

$(window).load(function() {
	imagesLoader();
});

function runOnDOMready() {
	common();
	lists();
	rollovers();
	products();
	locations();
	library();
	customDropDown();
	myfolder();
	alerts();
	showMenus();
	cycle_galery();
	promotion();
	resizePopup();
}


/* -------------------------------------------------------------- 
Menus for non pages
-------------------------------------------------------------- */
function showMenus() {
	var queryString = document.location.toString();
	var queryParameters = '';
	if (queryString.indexOf('?menu=') > 0) {
		var itemPassed = queryString.substring((queryString.indexOf('?menu=') + 6));
		if (itemPassed.length > 0) {
      if (itemPassed == "products") {

				var el = $('#nav').children('li.products').children('a');
				var klass = el.parent("li").attr("class");
				klass = filterClasses(klass);
				dd_Klass = ".dropdown-" + klass;

						// none already open, just open one up
						el.parent("li").addClass("dropdown");
						$(".navContainer").addClass("dd-open");
						//
						if (el.parent().parent().find("li.current").length > 0) {
							currentWas = filterClasses(el.parent().parent().find("li.current").attr("class"));
							el.parent().parent().find("li.current").removeClass("current");
							ieNavClasses();
						}
						//
						$(dd_Klass).slideDown("normal", function(){
							ieNavClasses();
							$(dd_Klass).addClass("dropdown-open");
							animating = false;
						});	

      } else if (itemPassed == "collections") {

				var el = $('#nav').children('li.collections').children('a');
				var klass = el.parent("li").attr("class");
				klass = filterClasses(klass);
				dd_Klass = ".dropdown-" + klass;

						// none already open, just open one up
						el.parent("li").addClass("dropdown");
						$(".navContainer").addClass("dd-open");
						//
						if (el.parent().parent().find("li.current").length > 0) {
							currentWas = filterClasses(el.parent().parent().find("li.current").attr("class"));
							el.parent().parent().find("li.current").removeClass("current");
							ieNavClasses();
						}
						//
						$(dd_Klass).slideDown("normal", function(){
							ieNavClasses();
							$(dd_Klass).addClass("dropdown-open");
							animating = false;
						});	
      }
	  }
  }
}

/* -------------------------------------------------------------- 
Specific Page-level functions
-------------------------------------------------------------- */

function imagesLoader() {
	
	if ($('.collections').length > 0) {
		
		var images = $('#content').children('.line').children('.size1of4').children('.entry').children('.entry-content').children('a').children('img');
		if (images.length > 0) {
			images.each(function(i) {
				var img = $(this);
				var imgSrc = img.attr('src');
				var link = img.parent('a');
			
				if (imgSrc.indexOf('no-image-177x177.gif') == -1) {
					img.fitToParent();
					if (img.height() < link.height()) {
						img.addClass('alignBottom').animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					} else {
						img.animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					}
				} else {
					img.animate({opacity: 1}, 800);
					link.css('background-image', 'none');
				}
				
			});
		}
	} 
	if ($('.detail').length > 0) {
		
		var images = $('#content').find('.subline').children('.size1of3').children('.entry').children('.entry-content').children('a').children('img');
		if (images.length > 0) {
			images.each(function(i) {
				var img = $(this);
				var imgSrc = img.attr('src');
				var link = img.parent('a');
				if (imgSrc.indexOf('no-image-145x145.gif') == -1) {
					img.fitToParent();
					if (img.height() < link.height()) {
						img.addClass('alignBottom').animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					} else {
						img.animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					}
				} else {
					img.animate({opacity: 1}, 800);
					link.css('background-image', 'none');
				}
				
			});
		}
	}	
	
	if ($('#libresults').length > 0) {
		
		var images = $('#libresults').find('.line').children('.size1of5').children('.entry').children('.entry-content').children('a').children('img');
		if (images.length > 0) {
			images.each(function(i) {
				var img = $(this);
				var imgSrc = img.attr('src');
				var link = img.parent('a');
				if (imgSrc.indexOf('no-image-145x145.gif') == -1) {
					img.fitToParent();
					if (img.height() < link.height()) {
						img.addClass('alignBottom').animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					} else {
						img.animate({opacity: 1}, 800);
						link.css('background-image', 'none');
					}
				} else {
					img.animate({opacity: 1}, 800);
					link.css('background-image', 'none');
				}
				
			});
		}
	}

	
}

function alerts() {
	if ($('#alerts').length > 0) {
		$('#alerts').find('p.close').click(function(e) {
			e.preventDefault();
			$('#alerts').slideUp('normal');
		});
	}
}


function myfolder() {
	
	if ($('.myfolder_actions').length > 0) {

		/* Email Pop up */
		var emailpop = $('.icon-action-email-pop');
		
		if($('.webkit').length > 0 || $('.chrome').length > 0) var height = 580;
		else var height = 520;
		
		emailpop.click(function(e) {
			e.preventDefault();
			emailpop = $(this);
			emailUrl = $(this).attr("href");
			pop(emailUrl, 'name', 500, height);
		});

		var myactions = $('.myfolder_actions');
		var holder_viewall = myactions.children('.first');
		var holder_selection = myactions.children('.last');
		
		holder_viewall.hover(function() {
			$(this).addClass('viewall_hover');
		}, function() {
			$(this).removeClass('viewall_hover');
		});
		
		holder_selection.hover(function() {
			$(this).addClass('rollover_col6');
		}, function() {
			$(this).removeClass('rollover_col6');
		});
		
		holder_selection.click(function(e) {
			e.preventDefault();
			var _parent = $(this).parent('ul').parent('.mod').parent('.unit').parent('.line');
			if (_parent.hasClass('chart_selected')) {
				if ($('#myfolder')[0]) {
					window.location = $(this).find('a.icon-selection').attr('href');
				} else {
					_parent.addToSelection(false);
				}
			} else {
				_parent.addToSelection(true);
			}
		});
	}
}

function library() {
	
	
	
	if ($('#library').length > 0) {
		
		
		
		// if ($('#library').hasClass('glossary')) {
		// 			
		// 			var items = $('#abc').children('li').length;
		// 			for (var i=1; i< 8; i++) {
		// 				$('#abc').children('li:nth-child('+i+')').addClass('adjust');
		// 			}
		// 			$('#abc').children('li:last').prev().addClass('adjust');
		// 			$('#abc').children('li:last').addClass('adjust');
		// 			
		// 			$('#abc').animate({opacity: 1}, 800);
		// 			
		// 			var dd = $('dd');
		// 			dd.each(function(i) {
		// 				var h = $(this).height();
		// 				var h2 = $(this).prev().height();
		// 				if (h2 > h) {
		// 					$(this).css('height', h2 + 'px');
		// 				}
		// 			});
		// 		}
		// 		
		if ($('#library').hasClass('publications')) {
			
			var line = $('#content').children('.line');
			var nbitems = line.children('.size1of4').length;
			
			for (var i=0; i <= nbitems; i++) {

				/* 1st item of each line */
				if ((i % 4) == 0) {
					line.children('.size1of4:nth-child('+ i + ')').next().css('clear', 'left');
				}
			}
			
		}
		
	}
}

function locations() {
	
	if ($('#locations').length > 0) {
		var line = $('#content').children('.line');
		var nbitems = line.children('.size1of4').length;
		
		for (var i=1; i <= nbitems; i++) {
			if (i <= 4 ) {
				line.children('.size1of4:nth-child('+ i + ')').children().addClass('firstfour');
			}
			
			/* 4th item of each line */
			if ((i % 4) == 0 ) {
				line.children('.size1of4:nth-child('+ i + ')').children().addClass('pos4');
			}
			
			/* 1st item of each line */
			if ((i % 5) == 0 || i == 1) {
				line.children('.size1of4:nth-child('+ i + ')').children().addClass('pos1');
			}
		}
		
		line.fadeIn('fast');
		
		/* Sidebar filter */
		// $('#triggerBoutiquePartner').click(function(e) {
		// 			e.preventDefault();
		// 			for (var i=1; i <= nbitems; i++) {
		// 				if ( line.children('.size1of4:nth-child('+ i + ')').find('dt').children('span').text() != 'Boutique Partner') {
		// 					line.children('.size1of4:nth-child('+ i + ')').fadeOut();
		// 				}
		// 				
		// 			}
		// 		});
		
		var test = '=Submit';
		var loc = window.location.href;
		if (loc.indexOf(test) != -1) {
			$('html,body').animate({scrollTop: $('#content').offset().top}, 800);
		}
		
	}
	
}

function products() {
	
	if ($('#products').length > 0) {
		
		$('#products.landing').children('#content').children('.line').each(function() {
			var cols = $('> *', this);
			var maxH = 0;
			cols.each(function() {
				var currentH = $(this).outerHeight(true); /* outerHeight returns height+padding+border, plus margin when set to true */
				maxH = (maxH > currentH) ? maxH : currentH;
			}).each(function() {
				$(this).animate({ 'height' : maxH}, 300);
			})
		});
		
		
		var animating = false;
		var currentWas = "";
		
		/* Update image tag in lightbox with the current image in slideshow */
		function updateLB(image) {
			//console.log(image.attr('src'));
			var lbImage = $('#lb').find('#enlargedHolder');
			lbImage.attr('src', image.attr('src'));
		}
		
		/* Bind click event on "View all products" link */
		$('#triggerProducts').click(function(e) {
			
			if (!animating) {
				animating = true;
				var el = $('#nav').children('li.products').children('a');
				var klass = el.parent("li").attr("class");
				klass = filterClasses(klass);
				dd_Klass = ".dropdown-" + klass;
				// check that the clicked option has a coressponding dropdown div
				// it does this off the name, not off the array index
				if ($(dd_Klass).length > 0) {
					e.preventDefault();
					if ($(".navContainer > ul li.dropdown").length > 0) {
						// one already open, so close it up, then open the next,
						// but wait, is this the same one being clicked?
						if (!el.parent("li").hasClass("dropdown")) {
							$(".navContainer > ul li.dropdown").removeClass("dropdown");
							el.parent("li").addClass("dropdown");
							//$(".navContainer").addClass("heightFix");
							ieNavClasses();
							$(".dropdown-open").fadeOut("normal", function(){																															
								$(".dropdown-open").removeClass("dropdown-open");
								// open next
								$(dd_Klass).fadeIn("normal", function(){	
									$(dd_Klass).addClass("dropdown-open");
									animating = false;							
								});
							});
						} else {
							// its the same, so close the open one
							$(".navContainer > ul li.dropdown").removeClass("dropdown");
							//$(".navContainer").removeClass("heightFix");
							ieNavClasses();
							$(".dropdown-open").slideUp("normal", function(){			
								$(".dropdown-open").removeClass("dropdown-open");
								$(".navContainer").removeClass("dd-open");
								if (currentWas != "") {
									$(".navContainer > ul li."+currentWas).addClass("current");
									ieNavClasses();
									currentWas = "";
								}
								animating = false;
							});
						}
					} else {
						// none already open, just open one up
						el.parent("li").addClass("dropdown");
						$(".navContainer").addClass("dd-open");
						//
						if (el.parent().parent().find("li.current").length > 0) {
							currentWas = filterClasses(el.parent().parent().find("li.current").attr("class"));
							el.parent().parent().find("li.current").removeClass("current");
							ieNavClasses();
						}
						//
						$(dd_Klass).slideDown("normal", function(){
							ieNavClasses();
							$(dd_Klass).addClass("dropdown-open");
							animating = false;
						});	
					}
				}				
			}
		});
		
		var refineon = $.cookie('refineon');
		if (refineon == 'true') {
			//console.log(refineon);
		}
		
		/* Bind click event on "Refine your search" */
		$('#triggerRefine').addClass('hover').click(function(e) {
			e.preventDefault();
			if ($('#refine').hasClass('refine-on')) {
				$.cookie('refineon', null);
				$('#refine').removeClass('refine-on');
				$('#refine').children('form').fadeOut('fast');
			} else {
				$.cookie('refineon', true);
				$('#refine').addClass('refine-on');
				$('#refine').children('form').fadeIn('fast');
			}
			
		});
		
		if ($('#products').hasClass('detail')) {
			
			var hasImage = true;
			
			/* Print Friendly */
			$('#print').click(function(e) {
				e.preventDefault();
				
				var print = window.open('', 'printWeb');
				print.document.open();
				print.document.write($);
				print.document.close();
			});
			
			if ($('#gallery_nav').children('.noimage').length == 0) {
				$('#gallery_caption').fadeIn()
				$('#gallery_nav').fadeIn();
				hasImage = true;
			} else {
				$('#gallery').addClass('noimage');
				hasImage = false;
			}
			
			/* Email Pop up */
			if($('.webkit').length > 0 || $('.chrome').length > 0) var height = 580;
			else var height = 520;
			
			var emailpop = $('.icon-action-email-pop');
			emailpop.click(function(e) {
				e.preventDefault();
				emailpop = $(this);
				emailUrl = $(this).attr("href");
				pop(emailUrl, 'name', 500, height);
			});
						
			var pageLoad = true;
			
			/* On page load, we load the gallery before we "reveal" it */
			$('#gallery_nav').galleria({
				insert 	  : '#gallery_container',
				history   : false,
				onImage   : function(image, caption, thumb) { 
							
								/* We activate the current thumbnail indicator */
								var current = $('#gallery_nav').children('li.active');
								if (!current.children('span')[0])
									current.append('<span></span>');
								
								/* We update the image source in the lightbox */
								//console.log('update');
								if (hasImage) { 
									updateLB(image);
									image.click(function(e) {
										e.preventDefault();
										if ($('#gallery').hasClass('enlarged')) {
											lightbox(false, 'gallery');
										} else {
											lightbox(true, 'gallery');
										}

									});
								}
								
								if ($('html').hasClass('ie7') || $('html').hasClass('ie8')) {
									image.each(function () {
									    image.fitToParent('gallery', pageLoad);
										if (pageLoad) 
											pageLoad = false;
										image.fadeTo('normal', 1);
									});
									$('#gallery_caption').fadeTo('normal', 1);
									$('#gallery_nav').fadeTo('normal', 1);
								} else {
									image.load(function () {
									    image.fitToParent('gallery', pageLoad);
										if (pageLoad) 
											pageLoad = false;
										image.fadeTo('normal', 1);

										$('#gallery_caption').fadeTo('normal', 1);
										$('#gallery_nav').fadeTo('normal', 1);

									});
								}
								
								
								
								
								$('#triggerEnlarge').click(function(e) {
									e.preventDefault();
									if ($('#gallery').hasClass('enlarged')) {
										lightbox(false, 'gallery');
									} else {
										lightbox(true, 'gallery');
									}
								});
								
								
								
							},
				clickNext : false
				
			});
			
			$('#gallery').show();
			
			/* Copy page intro into lightbox currently hidden at bottom */
			var txt = $('#page_intro').find('table').html();
			$('#lb').find('table').html(txt);
			
			if ($('#products').hasClass('detailStudio')) {
				$('#lb').addClass('detailStudio');
			}
			
			/* Options Chart */
			if ($('#chart')[0]) {
				var chart = $('#chart');
				chart.find('.expanded').prev('.chart_line').addClass('prev_expanded');
				chart.find('.expanded').next('.chart_line').addClass('prev_expanded');
				
				var chartLine = chart.children('.chart_line');
				var chartLine_alt = chart.children('.chart_line').children('.chart_line_top').children().not('.chart_col6');
				var chartLine_alt_collapsed = $('#chart').children(':not(.expanded)').children('.chart_line_top').children().not('.chart_col6');
				var chartLine_alt_expanded = $('#chart').children('.expanded').children('.chart_line_top').children().not('.chart_col6');
				var chartLine_top = $('#chart').children().not('.expanded').children('.chart_line_top').children().not('.chart_col6');
				
				var chartCol6 = chart.children('.chart_line').children('.chart_line_top').children('.chart_col6');

				chartLine_alt.hover(function() {
					var _chartLine = $(this).parent('ul').parent('.chart_line');
					if (!_chartLine.hasClass('expanded')) {
						_chartLine.rollover(true);
					} else {
						
					}
				}, function() {
					var _chartLine = $(this).parent('ul').parent('.chart_line');
					_chartLine.rollover(false);
				});
				
				chartLine_alt.click(function(e) {
					e.preventDefault();
					if (!animating) {
						// $(this).qtip("hide"); // Hides the tooltip
						
						var _chartLine = $(this).parent('ul').parent('.chart_line');
						_chartLine.prevAll().collapse();
						_chartLine.nextAll().collapse();
						if (_chartLine.hasClass('expanded')) {
							_chartLine.collapse();
						} else {
							_chartLine.expand();
						}
					}
				});
				
				chartCol6.hover(function() {
					$(this).subrollover(true);
				}, function() {
					$(this).subrollover(false);
				});
				
				chartCol6.click(function(e) {
					e.preventDefault();
					var _chartLine = $(this).parent('ul').parent('.chart_line');
					if (_chartLine.hasClass('folder_loggedin')) {
						if (_chartLine.hasClass('chart_selected')) {
							_chartLine.addToSelection(false);
						} else {
							_chartLine.addToSelection(true);
						}
					} else {
					  item_id = $(this).children('p').children('a').attr("rel");
						$('html,body').animate({scrollTop: 0}, 1000, function() {
              				$('#add_on_login_id').attr('value', item_id);
							$('#triggerMyFolder').animate({backgroundColor: '#FFF', color: '#1f2122'}, 400);
							$('#myfolderbar').addClass('active').slideDown('normal', function() {
								$('#myfolderbar').fadeTo('normal', 1);
							});
						});
					}
				});
				
				/* Finishing options trigger */
				$('.chart_options').find('a').click(function(e) {
					e.preventDefault();
					_href = $(this).attr("href");
					lightbox(true, _href);
				});
				
				var t = null;
				var offsetY = 12;
				var offsetX = -185; 
				
				
				if ($('html').hasClass('ie')) {
					offsetX = -220;
				} else 	if ($('html').hasClass('mac') && $('html').hasClass('gecko') ) {
					offsetY = 10;
					offsetX = -260;
				} else 	if ($('html').hasClass('mac') && $('html').hasClass('safari') ) {
					offsetY = 10;
					offsetX = -185;
				} else 	if ($('html').hasClass('mac') && $('html').hasClass('chrome') ) {
					offsetY = 10;
					offsetX = -202;
				}
				
				var hideT;
				function hideTooltip() {
					$('#chart-hover').css("cursor", "default").fadeOut();
				}
				
				var myToolTip;
				chartLine_alt.each(function(i) {
					if (!myToolTip) {
						myToolTip = '<div id="chart-hover" style="display:none">View details</div>';
						$('body').append(myToolTip);
					} 
					my_tooltip = $('#chart-hover');
					$(this).mouseover(function(){
						if (!($(this).parent().parent().hasClass('expanded'))) {
							hideT = setTimeout(hideTooltip, 3000);
							my_tooltip.css({display:"none"}).show();
						}
					}).mousemove(function(kmouse){
						my_tooltip.css({left:kmouse.pageX-5, top:kmouse.pageY+20});
					}).mouseout(function(){
						my_tooltip.hide();
						clearTimeout(hideT);
					});
				});
				
				
				/* Chart filters */
				var select = $('#chart_header').children('li').children('select');
				select.change(function() {
					var filterKlass = $(this).parent().attr('class');
					var filterAttribute = $(this).val();
					$('.chart_line').reveal();
				});
				
				
				/* Here we select available options for passed in item */
				var queryString = document.location.toString();
				var queryParameters = '';
				if (queryString.indexOf('?sku=') > 0) {
					/* We store the query parameters */
					var itemPassed = queryString.substring((queryString.indexOf('?sku=') + 5));
					if (itemPassed.length > 0 && $('#' + itemPassed)[0] ) {
						$('.chart_line').hide();
						$('html,body').animate({scrollTop: $('#' + itemPassed).offset().top - 30}, 800);
						$('#' + itemPassed).expand();
						var options = $('#' + itemPassed).children('.chart_line_top').children('li');
						options.each(function(i) {
							var option = $(this);
							var optionVal = option.text();
							var optionKlass = option.attr('class');
							$('#chart_header').children('.' + optionKlass).children('select').val(optionVal);
						});
						
					}
				}
			}
		
		}
	}
}

function clearRollover() {
	$('.chart_line').removeClass('rollover').removeClass('rollover_prev_expanded').removeClass('prev_rollover').removeClass('next_rollover');
}




jQuery.fn.reveal = function() {
	var $first = true;
	
	var filter = $('#chart_header').children('li');
	
	return this.each(function(i){
		var match = false;
		
		var line = $(this);
		var cols = line.children('.chart_line_top').children('li');
		
		var filters = $('#chart_header').children('li').children('select');
		
		
		filters.each(function(i) {
			var filter = $(this);
			var filterKlass = filter.parent().attr('class');
			var filterVal = filter.val();
			//console.log('(' + i + ')' + filterVal + '-' + filterKlass);
			if (filterVal.length > 0) {
				if (filterVal == line.children('.chart_line_top').children('li.' + filterKlass).html()) {
					//console.log('bingo: fiterVal=' + filter.val());
					match = true;
				} else {
					//console.log('failed: fiterVal=' + filter.val());
					match = false;
					return false;
				}
			} else {
				match = true;
			}
			
		});
		
		
		if (match) {
			line.removeClass('first_chart_line');
			line.collapse().slideDown();
			line.addClass('filtered')
			$('#chart').children('.filtered:first').addClass('first_chart_line');
		} else {
			line.removeClass('first_chart_line').removeClass('filtered');
			line.collapse().slideUp();
			
		}
		
		
	});	

	
};


jQuery.fn.expand = function() {
	return this.each(function(i){
		$(this).show();
		clearRollover();
		$(this).children('.chart_line_bottom').slideDown();
		$(this).addClass('expanded');
		$(this).prev('.chart_line:visible').addClass('prev_expanded');
		$(this).next('.chart_line:visible').addClass('next_expanded');
		
		if ($(this).next('.chart_line:visible').hasClass('expanded')) {
		 	$(this).addClass('expanded_alt');
		}
		
		if ($(this).prev('.chart_line:visible').hasClass('expanded')) {
		 	$(this).prev().addClass('expanded_alt');
		}
		
		//$('html,body').animate({scrollTop: $(this).offset().top}, 500);
		$('#chart-hover').css("cursor", "default").hide();
	});	
};

jQuery.fn.collapse = function() {
	return this.each(function(i){
		$(this).children('.chart_line_bottom').slideUp();
		$(this).removeClass('expanded').prev('.chart_line:visible').removeClass('prev_expanded');
		$(this).next('.chart_line:visible').removeClass('next_expanded');
		
		$(this).removeClass('expanded_alt');
		
		$(this).prev('.chart_line:visible').removeClass('expanded_alt');
		
	});	
};

jQuery.fn.rollover = function(on) {
	return this.each(function(i){
		var previousChartLine = $(this).prev('.chart_line:visible');
		var nextChartLine = $(this).next('.chart_line:visible');
		if (on) {
			
			if ($(this).hasClass('prev_expanded')) {
				$(this).addClass('rollover_prev_expanded');
			} else {
				$(this).addClass('rollover');
			}
			previousChartLine.addClass('prev_rollover');
			
			if (nextChartLine.hasClass('expanded')) {
				nextChartLine.addClass('next_rollover');
			}
			
		} else {
			$(this).removeClass('rollover');
			$(this).removeClass('rollover_prev_expanded');
			previousChartLine.removeClass('prev_rollover');
			nextChartLine.removeClass('next_rollover');
		}
		
		
	});	
};

jQuery.fn.subrollover = function(on) {
	return this.each(function(i){
		//var index = $(this).prevAll().length +1;
		var thisChartLine = $(this).parent().parent('.chart_line');
		var previousChartLine = thisChartLine.prev('.chart_line:visible');
		var nextChartLine = thisChartLine.next('.chart_line:visible');
		if (on) {
			thisChartLine.addClass('rollover_col6');
			
			if (previousChartLine.hasClass('expanded') && !thisChartLine.hasClass('expanded')) {
				previousChartLine.children('.trick').show();
			} else {
				previousChartLine.addClass('prev_rollover_col6');
			}
			
			if (!thisChartLine.hasClass('expanded') && nextChartLine.hasClass('expanded')) {
				nextChartLine.addClass('next_rollover_col6');
			}
		} else {
			previousChartLine.children('.trick').hide();
			thisChartLine.removeClass('rollover_col6');
			previousChartLine.removeClass('prev_rollover_col6');
			nextChartLine.removeClass('next_rollover_col6');
		}
		
		
	});	
};

jQuery.fn.addToSelection = function(select) {
	return this.each(function(i){
		
		var icon = $(this).find('.icon-selection');
		var text = $(this).find('.text-selection');
		var bgtext = text.css('background-color');
		var itemid = icon.attr('rel');
		
		animating = true;
		if (select) {
			/* add to selection */
			// make ajax call /myselection/additem/<id>

			$.get("/myselection/additem/"+itemid, function(data){
			  updateFolderCount(data);
			});

			$(this).addClass('chart_selected');
			
			icon.animate({opacity: 0}, 200, function() {
				icon.addClass('icon-selected').animate({opacity: 1}, 200);
			});
			
			text.animate({color: bgtext}, 200, function() {
				text.html('Remove from my folder');
				text.animate({color: '#FFF'}, 200);
			});
			
		} else {
			/* remove it from selection */
			// make ajax call /myselection/removeitem/<id>

			$.get("/myselection/removeitem/"+itemid, function(data){
			  updateFolderCount(data);
			});

			$(this).removeClass('chart_selected');
			
			icon.animate({opacity: 0}, 200, function() {
				icon.removeClass('icon-selected').animate({opacity: 1}, 200);
			});
			
			text.animate({color: bgtext}, 200, function() {
				text.html('Add to my folder');
				text.animate({color: '#FFF'}, 200);
			});
		}
		animating = false;
		
	});	
};

function updateFolderCount(response) {
	// TODO
	var mySplitResult = response.split(":");
	var code = mySplitResult[0];
	var count = mySplitResult[1];
	var text = $('#myfoldernb');
	text.html(count);	
}

function lightbox(on, param) {
	
	function showMask() {
		
		if (param == 'gallery') {
			$('#gallery').toggleClass('enlarged');
			$('#lb').removeClass('color');
			$('#lb').find('#page_description').children('p').show('fast');
		} else {
			$('#lb').find('#page_description').children('p').hide('fast');
			if (param != "" || param != "#") {
				$("#optionsHolder").load(param, function() {
					$('#lb').addClass('color');

					$('.color').find('.size1of6').find('a').hover(function() {
						$(this).next().children('a').addClass('color-hover');
					}, function() {
						$(this).next().children('a').removeClass('color-hover');
					});
				});
				
				
			}
		}
		
		if ($('html').hasClass('ie')) {
			var h = $('.page').height();
			$('#lb_mask').height(h);
			$('#lb_mask').show();
		}
		else {
			$('#lb_mask').show();
		}
		$('html,body').animate({scrollTop: 0}, 500, function() {
			$('#lb').fadeIn('fast');
			if (param == 'gallery') {
				$('#enlargedHolder').show();
				$('#lb').css('width', '985px').children('img').fitToParent('full');
			} else {
				$('#optionsHolder').show();
			}
			
		});
		
	}
	
	function hideMask(param) {
		$('#gallery').removeClass('enlarged');
		
		$('#lb_mask').fadeOut();
		$('#lb').fadeOut('normal', function() {
			$('#enlargedHolder').css('display', 'none');
			$('#optionsHolder').css('display', 'none');
		});
	}
	
	$('#lb_close').click(function(e) {
		e.preventDefault();
		hideMask();
	})
	
	/* turn on lightbox */
	if (on) {
		showMask();
	} 
	/* turn off lightbox */
	else {
		hideMask();
	}
	
} 

jQuery.fn.vAlign = function() {
	return this.each(function(i){
	var h = $(this).height();
	var oh = $(this).outerHeight();
	var mt = (h + (oh - h)) / 2;	
	$(this).css("margin-top", "-" + mt + "px");	
	$(this).css("top", "50%");
	$(this).css("position", "absolute");	
	});	
};


jQuery.fn.hAlign = function() {
	return this.each(function(i){
	var w = $(this).width();
	var ow = $(this).outerWidth();	
	var ml = (w + (ow - w)) / 2;	
	$(this).css("margin-left", "-" + ml + "px");
	$(this).css("left", "50%");
	$(this).css("position", "absolute");
	});
};

jQuery.fn.fitToParent = function(transition, firstload)
{
    this.each(function()
    {
       var maxWidth = $(this).parent().width();
		var maxHeight = $(this).parent().height();
		
		if (transition == 'full') {
			maxWidth = 985;
		}
		if (transition == 'gallery') {
			maxHeight = 600;
		}
		
		$('#lb').css('width', '985px');

		
		var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height

		if(width > maxWidth){
			ratio = maxWidth / width;   // get ratio for scaling image
			if (transition) {
				$(this).animate({width: maxWidth, height: height * ratio});
			} else {
				$(this).css("width", maxWidth); // Set new width
				$(this).css("height", height * ratio);  // Scale height based on ratio
			}
			height = height * ratio;    // Reset height to match scaled image
			width = width * ratio;    // Reset width to match scaled image
		}



		if (transition == 'gallery') {
			
			//Check if current height is larger than max
			if(height > maxHeight ){
				$(this).parent().attr('align', 'center');
				ratio = maxHeight / height; // get ratio for scaling image
			if (transition) {
			 	$(this).animate({height: maxHeight, width: width * ratio});
			 } else {
				$(this).css("height", maxHeight);   // Set new height
					            $(this).css("width", width * ratio);    // Scale width based on ratio
			}
				height = maxHeight;
				width = width * ratio;    // Reset width to match scaled image
			}

			// if(height > maxHeight) {
			// 	height = 600;
			// }
			
			if ($('html').hasClass('ie6') || $('html').hasClass('ie7')) {
				height = height + 5;
			}
			
			if (firstload) {
				$('.galleria_ghost').css("height", height).show(); 
				$('.galleria_ghost').children('span').show();
				$(this).parent().css("height", height);
			} else {
				$('.galleria_ghost').css("height", height); 
				$(this).parent().animate({ height: height}, 1000);
			}
		}
		
		if (transition)
			$('#gallery').parent().parent().removeClass('enlarged');
		
		//$('.galleria_ghost').remoClass('ghostoff');
		
    });
};

jQuery.fn.enlarge = function()
{
    this.each(function()
    {
        var maxWidth = 985; // Max width for the image
        var ratio = 0;  // Used for aspect ratio
        var width = $(this).width();    // Current image width
        var height = $(this).height();  // Current image height
        ratio = maxWidth / width;   // get ratio for scaling image
		$('#gallery').parent().parent().toggleClass('enlarged');
		$(this).animate({width: maxWidth, height: height * ratio});
    });
};



	
/* -------------------------------------------------------------- 
Common Page-level functions
-------------------------------------------------------------- */
function common() {
	ieNavClasses();
	dropdowns();
	navsearch();
	
	$("input[type=submit]").hover(function(){
		$(this).addClass("submitHover");
	}, function() {
		$(this).removeClass("submitHover");
	});
	
	$('#myfolderbar').css('opacity', 0);
	$('#triggerMyFolder').click(function(e) {
		e.preventDefault();
		if (!$('#myfolderbar').hasClass('active')) {
			$(this).parent().addClass('active');
			$('#myfolderbar').addClass('active').slideDown('normal', function() {
				$('#myfolderbar').fadeTo('normal', 1);
				$('#myfolder_name').focus();
			});
		} else {
			$(this).parent().removeClass('active');
			$('#myfolderbar').removeClass('active').fadeTo('fast', 0, function() {
				$('#myfolderbar').slideUp('normal');
				
			});
		}
		$('#alerts').slideUp();
	});
	
	$('#triggerMyFolder').hover(function() {
		$(this).parent().addClass('hover');
	}, function() {
		$(this).parent().removeClass('hover');
	});
	
	var myclose = $('#myfolderbar').find('input.cancel');
	myclose.hover(function() {
		$(this).addClass('myfolderclose-hover');
	}, function() {
		$(this).removeClass('myfolderclose-hover');
	});
	myclose.click(function(e) {
		$('#myfolderbar').removeClass('active').fadeTo('fast', 0, function() {
			$('#triggerMyFolder').animate({backgroundColor: '#27292A', color: '#656363'}, 400);
			$('#myfolderbar').slideUp('normal');
			
		});
		$('#triggerMyFolder').parent().removeClass('active');
	});
	
	if ($('#alerts')[0] && $('#alerts').is(':visible') ) {
		
		function closeAlerts() {
			$('#alerts').slideUp('slow');
		}
		
		setTimeout(closeAlerts, 3000)
	}
	
	if ($('ul.contact')[0]) {
		if ($('input[name=contact_first_name]').val() == '') {
			$('input[name=contact_first_name]').focus();
		}
	}
}

/* -------------------------------------------------------------- 
Specific Module functions
-------------------------------------------------------------- */

function lists() {
	if ($('.simpleList')[0]) {
		
		$('.simpleList').children('li').css('z-index', '99');
		
		$('.simpleList').children('li:first-child').addClass('first');
		
		
		$('.simpleList').children('li:not(:first-child)').hover(function() {
			if ($(this).children('a').length > 0 ) {
				if (!$(this).parent().hasClass('dropdown-selected')) {
					$(this).addClass('dropdown-hover');
				}
				
			}
		}, function() {
			if ($(this).children('a').length > 0 ) {
				$(this).removeClass('dropdown-hover');
				$(this).removeClass('dropdown-hover-alt');
			}
		});
		
		$('#primarySidebar').children('.simpleList').children('li').hover(function() {
			if ($(this).children('a').length > 0 ) {
				if (!$(this).parent().hasClass('dropdown-selected')) {
					$(this).addClass('dropdown-hover');
					$(this).next().addClass('dropdown-next-hover');
				}
				
			}
		}, function() {
			if ($(this).children('a').length > 0 ) {
				$(this).removeClass('dropdown-hover');
				$(this).removeClass('dropdown-hover-alt');
				$(this).next().removeClass('dropdown-next-hover');
			}
		});
	}
	
	if ($('#primarySidebar')[0]) {
		
		$('#primarySidebar').children('.simpleList').find('.dropdown-current').next().addClass('dropdown-next-hover');
		
	}
	
	if ($('.paginator')[0]) {
		$('.paginator').children('li:not(li.prevnext):first').addClass('first');
		
		$('.paginator').children('li').hover(function() {
			if ($(this).children('a')[0])
				$(this).addClass('page-hover');
		}, function() {
			if ($(this).children('a')[0])
				$(this).removeClass('page-hover');
		});
		
		if ($('.prev').hasClass('disabled')) {
			$('.prev').children('span').addClass('prevdisabled');
		} else {
			$('.prev').children('span').removeClass('prevdisabled');
		}
		
	}
	
	if ($('#breadcrumb')[0]) {
		$('#breadcrumb').children('li:first-child').addClass('first');
		
	}
	
	if ($('.customDropDown')[0]) {
		$('.customDropDown').find('ul').children('li:last-child').addClass('last');
	}
}

function rollovers() {
	
	if ($('.listing')[0] || $('.detail')[0]) {
		
		$('.entry').hover(function() {
			$(this).addClass('entry-hover');
		}, function() {
			$(this).removeClass('entry-hover');
		});
		
	}
	
	if ($('#features')[0]) {
		
		$('#features').find('.entry-content').children('a').hover(function() {
			$(this).parent().parent().addClass('entry-hover');
		}, function() {
			$(this).parent().parent().removeClass('entry-hover');
		});
		
	}
	
	if ($('p.close')[0]) {
		$('p.close').hover(function() {
			$(this).addClass('close-hover');
		}, function() {
			$(this).removeClass('close-hover');
		});
		
	}
	
}

function navsearch() {
	
	
	
	var search = $('.navContainer').children('form');
	
	if ($('#store').length > 0) {
		search = $('#store').children('.header').children('form');
	}
	
	search.hover(function(){
		$(this).addClass("form-hover");
	}, function() {
		$(this).removeClass("form-hover");
	});
	
	search.find('input[type=text]').focus(function(e){
		//if ($(e.target).val() == "Rechercher") {
			search.addClass("searchFor");			
		//}
	});
	search.find('input[type=text]').blur(function(e){
		if ($(e.target).val() == "") {
			search.removeClass("searchFor");
		}
	});
	
	if (search.find('input[type=text]').val() != "") {
		if ($('html').hasClass('ie6') && $('html').hasClass('ie7')) {
			var height = search.find('input[type=text]').height();
			if (height != 26) {
				search.find('input[type=text]').css('height', '26px');
			}
		}
		search.addClass("searchFor");
	}
	
	
	search.find('input').animate({opacity: 1}, 800);
	
	
}



/* -------------------------------------------------------------- 
Core functions
-------------------------------------------------------------- */

function filterClasses(klass) {
	if ($('html').hasClass('ie6')) {
		klass = replaceAll(klass, ieNavClass[0], "");
		klass = replaceAll(klass, ieNavClass[1], "");
	}
	klass = replaceAll(klass, "first", "");
	klass = replaceAll(klass, "last", "");
	klass = replaceAll(klass, "even", "");
	klass = replaceAll(klass, "current", "");
	klass = replaceAll(klass, "dropdown", "");
	klass = replaceAll(klass, " ", "");
	return klass;
}

var ieNavClass = new Array();
function ieNavClasses() {
	// function to sort fix IE6's lack of multiple CSS class selector
	if ($('html').hasClass('ie6')) {
		//
		$("."+ieNavClass[0]).removeClass(ieNavClass[0]);
		$("."+ieNavClass[1]).removeClass(ieNavClass[1]);
		//
		$(".navContainer ul li.current").each(function(i,val) {
			var klass = $(this).attr("class");
			klass = filterClasses(klass);
			klass = klass + "-current";
			$(this).addClass(klass);
			ieNavClass[0] = klass;
		});
		$(".navContainer ul li.dropdown").each(function(i,val) {
			var klass = $(this).attr("class");
			klass = filterClasses(klass);
			klass = klass + "-dropdown";
			$(this).addClass(klass);
			ieNavClass[1] = klass;
		});
	}
}

function dropdowns() {
	var animating = false;
	var currentWas = "";
	//
	
	$('#nav').children('li').children('a').each(function(i,val){
		
		$(this).click(function(e) {
			
			var fil = $(this).html();
			
			if (!animating && (fil == 'COLLECTIONS' || fil == 'PRODUCTS')) {
				animating = true;
				var el = $(this);
				var klass = el.parent("li").attr("class");
				klass = filterClasses(klass);
				dd_Klass = ".dropdown-" + klass;
				// check that the clicked option has a coressponding dropdown div
				// it does this off the name, not off the array index
				if ($(dd_Klass).length > 0) {
					e.preventDefault();
					if ($(".navContainer > ul li.dropdown").length > 0) {
						// one already open, so close it up, then open the next,
						// but wait, is this the same one being clicked?
						if (!el.parent("li").hasClass("dropdown")) {
							$(".navContainer > ul li.dropdown").removeClass("dropdown");
							el.parent("li").addClass("dropdown");
							//$(".navContainer").addClass("heightFix");
							ieNavClasses();
							$(".dropdown-open").fadeOut("normal", function(){																															
								$(".dropdown-open").removeClass("dropdown-open");
								// open next
								$(dd_Klass).fadeIn("normal", function(){	
									$(dd_Klass).addClass("dropdown-open");
									createVerticalLine($(dd_Klass));
									$('.dropdown-open').children('p.close').fadeIn('normal');
									animating = false;							
								});
							});
						} else {
							// its the same, so close the open one
							$('.dropdown-open').children('p.close').fadeOut(100);
							$(".navContainer > ul li.dropdown").removeClass("dropdown");
							//$(".navContainer").removeClass("heightFix");
							ieNavClasses();
							$(".dropdown-open").slideUp("normal", function(){			
								$(".dropdown-open").removeClass("dropdown-open");
								$(".navContainer").removeClass("dd-open");
								if (currentWas != "") {
									$(".navContainer > ul li."+currentWas).addClass("current");
									ieNavClasses();
									currentWas = "";
								}
								animating = false;
							});
						}
					} else {
						// none already open, just open one up
						el.parent("li").addClass("dropdown");
						$(".navContainer").addClass("dd-open");
						//
						if (el.parent().parent().find("li.current").length > 0) {
							currentWas = filterClasses(el.parent().parent().find("li.current").attr("class"));
							el.parent().parent().find("li.current").removeClass("current");
							ieNavClasses();
						}
						//
						$(dd_Klass).slideDown("normal", function(){
							ieNavClasses();
							$(dd_Klass).addClass("dropdown-open");
							createVerticalLine($(dd_Klass));
							$('.dropdown-open').children('p.close').fadeIn('normal');
							animating = false;
						});	
					}
				}				
			}
		});
	
	});
	
	$(".navContainer").find("p.close").click(function(e) {
		e.preventDefault();
		$('.dropdown-open').children('p.close').fadeOut(100);
		$(".navContainer > ul li.dropdown").removeClass("dropdown");
		//$(".navContainer").removeClass("heightFix");
		ieNavClasses();
		$(".dropdown-open").slideUp("slow", function(){
			$(".dropdown-open").removeClass("dropdown-open");
			$(".navContainer").removeClass("dd-open");
			if (currentWas != "") {
				$(".navContainer > ul li."+currentWas).addClass("current");
				ieNavClasses();
				currentWas = "";
			}
		});
	});
	
	$('.dropdown').children('p.close').hover(function() {
		$(this).addClass('close-hover');
	}, function() {
		$(this).removeClass('close-hover');
	});
}

function createVerticalLine(elem) {
	if (elem.hasClass('dropdown-collections')) {
		var height = $('.pixel').parent().height();
		$('.pixel').css({'height' : height + 'px'});
		$('.pixel').show('fast');
	} 
	
}

// this function search and replaces a string and returns the new string
// http://www.daveshuck.com/blog/index.cfm/2006/12/13/Javascript-examples--removeElement-and-replaceAll
function replaceAll( str, searchTerm, replaceWith, ignoreCase )   {
   var regex = "/"+searchTerm+"/g";
   if( ignoreCase ) regex += "i";
   return str.replace( eval(regex), replaceWith );
}

function searchVersion(browser) {
	var dataString = navigator.userAgent;
	var index = dataString.indexOf(browser);
	if (index == -1) return;
	var bVersion = parseFloat(dataString.substring(index+browser.length+1));
	return bVersion.toString().split(".")[0];
}

/* CustomDropDown
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function customDropDown() {
	
	$(".customDropDown").each(function (i) {
		
		var isLong = false;
		var ul = $(this).find('ul');
		var isEmpty = false;
		ul.children('li:first-child').addClass('first');
		var liSize = ul.children().size();
		if (liSize == 0) {
			isEmpty = true;
		}
		else if (liSize > 15) {
			isLong = true;
		}
		
		$(this).find("h5").addClass("hover");

		var ddInput = $(this).children()[0];
		var ddDiv = $(this).children()[1];
		//
		ddInput = $(ddInput);
		ddDiv = $(ddDiv);
		//
		ddDiv.hide();
		//
		var clickFunction = $(this).attr("id");
		//
		ddInput.click(
			function () {
				if (!isEmpty) {
					//if (isLong) ul.addClass('long');
					toggleDD();
				}
				else {
					alert("No options available for this criteria.");
				}
			}
		);
		
		function toggleDD() {
			if (ddDiv.hasClass('dd-open')) {
				if (ddDiv.hasClass('dd-selected')) {
					if (ddDiv.find('.dd-hide')[0]) {
						ddDiv.find('.dd-hide').removeClass('dd-hide').show();
						ddDiv.prev().addClass('wborder');
						if (isLong)
							ddDiv.children('ul').addClass('long');
						
					} else {
						ddDiv.find('li:not(.selected)').addClass('dd-hide');
						ddDiv.prev().removeClass('wborder');
						if (isLong)
							ddDiv.children('ul').removeClass('long');
					}
				} else {
					ddDiv.slideUp('fast');
					ddDiv.removeClass('dd-open');
					ddDiv.prev().removeClass('dd-open').removeClass('wborder');
					
				}
			} else {
				if (isLong)
					ddDiv.children('ul').addClass('long');
				ddDiv.find('li').show();
				ddDiv.slideDown('fast');
				ddDiv.addClass('dd-open');
				ddDiv.prev().addClass('dd-open').addClass('wborder');
				
			}
		}
		
		/* Bind click events */
		ddDiv.find('li').click(function(e) {
			e.preventDefault();
			// if itself is already been selected, we show all options
			if ($(this).hasClass('selected')) {
				$(this).parent().parent().parent().removeClass('option_selected');
				$(this).parent().parent().removeClass('dd-selected').show(); 
				$(this).removeClass('selected');
				
				$(this).parent().parent().slideUp('fast');
				$(this).parent().parent().removeClass('dd-open');
				$(this).parent().parent().prev().removeClass('dd-open');
				
				$(this).parent().find('.dd-hide').removeClass('dd-hide');
				
				$(this).parent().parent().prev().removeClass('wborder');
				
			} else {
				$(this).parent().parent().parent().addClass('option_selected');
				$(this).parent().parent().addClass('dd-selected'); 
				$(this).parent().find('.selected').removeClass('selected');
				$(this).removeClass('dd-hide').addClass('selected');
				$(this).parent().find('li:not(.selected)').addClass('dd-hide');
				
				$(this).parent().parent().prev().removeClass('wborder');
				
				if (isLong)
					$(this).parent().removeClass('long');
			}
		});
		
		/* Hover click events */
		ddDiv.find('li').hover(function() {
			if (ddDiv.hasClass('dd-selected')) {
				if (!$(this).hasClass('selected')) {
					$(this).addClass('dd-hover-alt');
				} else {
					$(this).addClass('dd-hover-selected');
				}
			} else {
				if ( $(this).hasClass('selected') && ddDiv.find('.dd-hide')[0] ) {
				} else {
					$(this).addClass('dd-hover');
					$(this).next().addClass('dd-hover-next');
					if ($(this).hasClass('.last')) {
						$(this).parent().parent().parent().addClass('customDropDownSelected');
					}
				}
			}
			
		}, function() {
			$(this).removeClass('dd-hover');
			$(this).removeClass('dd-hover-alt')
			$(this).removeClass('dd-hover-selected');
			$(this).parent().children().removeClass('dd-hover-next');
			$(this).parent().parent().parent().removeClass('customDropDownSelected');
		})
		
		
	});
	
	$('#refine').children('form').submit(function() {
		
		var input_one = $('input[name=attribute_1]');
		var input_two = $('input[name=attribute_2]');
		var input_three = $('input[name=attribute_3]');
		var input_four = $('input[name=attribute_4]');
		
		var option_one = $('#attribute_1').find('.selected');
		var option_two = $('#attribute_2').find('.selected');
		var option_three = $('#attribute_3').find('.selected');
		var option_four = $('#attribute_4').find('.selected');
		
		if (option_one.length > 0) {
			input_one.attr('value', option_one.attr('id'));
		}
		
		if (option_two.length > 0) {
			input_two.attr('value', option_two.attr('id'));
		}
		
		if (option_three.length > 0) {
			input_three.attr('value', option_three.attr('id'));
		}

		if (option_four.length > 0) {
			input_four.attr('value', option_four.attr('id'));
		}
			
		// if (option_one.length == 0 && option_two.length == 0 && option_three.length == 0) {
		// 			alert("Please select one attribute at least");
		// 			return false;
		// 		} 
			
	});
	
}


// CREATING THE HOME GALERY

function cycle_galery() {
	
	if($('#caroussel').length === 0) return false;
	
 	var number = $('img', '#caroussel').length;
	var previous = 0;
	// SETTING UP THE GALERY
	$('#caroussel').cycle({ 
			fx:    		'fade', 
			speed:  	1000,
			pause:  	1,
			timeout: 	7000,
			startingSlide: previous,
			next:   	'#next',
			prev:   	'#prev',
			before:   updateText,
			after:    updateSize
	 });

	 if(number == 1) {
	 		$('#text_highlights'+previous).fadeIn('200');
	 		$('#next').hide();
	 		$('#prev').hide();
	 	}
   
	 	function updateText(curr, next, opts){
	 	   var img = this, link = $(this).attr('rel');
	 			$('#text_highlights'+previous).hide(10, function() {
	 				$('#text_highlights'+opts.currSlide).show();
	 			});
	 	}
	 	
	 	function updateSize(curr, next, opts) {
	 			previous = opts.currSlide;
	 	}
}


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/*------ PROMOTION -------*/

function promotion() {
	
	if($('.promotion-pop').length === 0) return false;
	
	/* Promotion Pop up */
	var promotion_pop = $('.promotion-pop');

	if($('.webkit').length > 0 || $('.chrome').length > 0) var height = 410;
	else var height = 350;
	
	promotion_pop.click(function(e) {
		e.preventDefault();
		popUrl = $(this).attr("href");

		pop(popUrl, 'name', 500, height);
	});
	
}
function resizePopup() {
	
	if($('.popupresizer').length === 0) return false;
	
	window.focus();
	
	var heightAdded = 0;
	
	if($("#sub").length > 0) heightAdded = $("#sub").height();
	else {
		heightAdded = $(".errors:first").height();
		if(heightAdded > 0) heightAdded = heightAdded + 40;
	}

	window.resizeBy(0, heightAdded);
}


function pop(url, name, width, height, scrollbars) {
	
	if (scrollbars == null) scrollbars = 'no';
	
	var style = (style == null) ? "standard" : style;
	var x = 0; var y = 0; var offset = 30;
	if (screen) { x = (screen.availWidth - width) / 2 };
	if (screen) { y = (screen.availHeight - height) / 2 };
	var popped = window.open(url,'popup','width='+width+',height='+(height)+',status=no,location=0,menubar=no,scrollbars=' + scrollbars + ',resizable=no,screenX='+x+',screenY='+y+',left='+x+',top='+y);
	if (!popped.opener) { popped.opener = window; }
	popped.focus();

}



