// rollOvers pour les images
// Application : class="roll"
window.addEvent('domready', function() {
	
	// ROLL OVER IMAGES
	//preload images
	var aPreLoad = new Array();
	var aPreLoadi = 0;
	
	$$('img.roll', 'input.roll').each(function(el){
		//let's preload
		aPreLoad[aPreLoadi] = new Image();
		aPreLoad[aPreLoadi].src = el.src.replace(el.src.replace('_off.', '_on.'));
		aPreLoadi++;
	
		el.addEvent('mouseover',function(){
			this.setAttribute('src',this.src.replace('_off.', '_on.'));
		});
	
		el.addEvent('mouseout',function(){
			this.setAttribute('src',this.src.replace('_on.','_off.'));
		});
	});
	
	// ROLL OVER TEXT
	// Application : class="rollText"
	$$('.rollText').each(function(el){
		var original = el.getStyle('color');
		var morph = new Fx.Morph(el,{ 'duration':'300' });
		el.addEvents({
			'mouseenter' : function() { morph.start({ 'color':'#ff8c00' }) },
			'mouseleave' : function() { morph.start({ 'color': original }) }
		});
	});
	
	// SHADOWBOX INIT
	var options = {
		animate: false,
		modal: true,
		handleOversize:     'none',
		handleUnsupported:  'remove',
		autoplayMovies:     false,
		overlayColor: '#ffffff',
		overlayOpacity: '0.2'
  };
	Shadowbox.init(options);
	
	// TWITTER (if box is found)
	if ($('latest_news_wrapper') != null) {
		getTwitters('atomBikes', {
			id: 'AtomBicycles',
			timeout: 2,
			onTimeout: function () {
					this.innerHTML = '<span class="twitterStatus">Les nouvelles ne sont pr&eacute;sentement pas disponibles!</span>';
			},
			onTimeoutCancel: true,
			ignoreReplies: true,
			template: '<span class="twitterStatus">"%text%"</span> <span class="twitterTime">%time% de <a href="http://www.twitter.com/AtomBicycles" target="_blank">Twitter</a></span>'
		});
	}
});

function showCart() {
	$('show_cart').setStyle('display', 'block');
	$('cart').addEvent('mouseleave', hideCart);
}

function makeCartVisible() {
	$('show_cart').setStyle('display', 'block');
}

function hideCart() {
	$('show_cart').setStyle('display', 'none');
	$('cart').removeEvent('mouseleave', hideCart);
}

function addToCart(id, title, price, type) {
	var updateCart = new Request({
		url: '../_ajax/cart.php',
		data: 'action=add&id='+escape(id)+'&type='+type,
		async: true,
		onSuccess: function() {
			if ($('cart_item_'+type+id) != null) {
				if (type == 'frenchie') {
					$('cart_item_'+type+frenchieReplace(id)+'_qty').set('html', parseInt($('cart_item_'+type+frenchieReplace(id)+'_qty').get('html'))+1);
				} else {
					$('cart_item_'+type+id+'_qty').set('html', parseInt($('cart_item_'+type+id+'_qty').get('html'))+1);
				}
			} else {
				if (type == 'frenchie') {
					var injectEl  = new Element('div', {id: 'cart_item_'+type+frenchieReplace(id), 'html': '\
						&raquo; <a href="../personnalise/popup.php'+id+'" rel="shadowbox;width=733;height=464">'+title+'</a><br />\
						<div align="right">\
							<span id="cart_item_'+type+frenchieReplace(id)+'_qty">1</span>x @ '+price+'$<br />\
							<a href="javascript://" onclick=\"removeFromCart(\''+id+'\', \''+type+'\');\"><img src="../_images/cart/bt_remove_f.png" width="71" height="14" alt="Supprimer" border="0" /></a>\
						</div>\
					'});
				} else {
					if (type == 'accessories') {
							var injectEl  = new Element('div', {id: 'cart_item_'+type+id, 'html': '\
							&raquo; <a href="../accessoires/popup.php?id='+id+'" rel="shadowbox;width=733;height=464">'+title+'</a><br />\
							<div align="right">\
								<span id="cart_item_'+type+id+'_qty">1</span>x @ '+price+'$<br />\
								<a href="javascript://" onclick=\"removeFromCart(\''+id+'\', \''+type+'\');\"><img src="../_images/cart/bt_remove_f.png" width="71" height="14" alt="Supprimer" border="0" /></a>\
							</div>\
						'});
					} else {
							var injectEl  = new Element('div', {id: 'cart_item_'+type+id, 'html': '\
							&raquo; <a href="../pieces/popup.php?id='+id+'" rel="shadowbox;width=733;height=464">'+title+'</a><br />\
							<div align="right">\
								<span id="cart_item_'+type+id+'_qty">1</span>x @ '+price+'$<br />\
								<a href="javascript://" onclick=\"removeFromCart(\''+id+'\', \''+type+'\');\"><img src="../_images/cart/bt_remove_f.png" width="71" height="14" alt="Supprimer" border="0" /></a>\
							</div>\
						'});
					}
					
				}
				injectEl.inject($('cart_content'));
				//Shadowbox.clearCache();
				Shadowbox.setup();
			}
			$('cart_items_qty').set('html', parseInt($('cart_items_qty').get('html'))+1 + " ITEMS<br/>S&Eacute;LECTIONN&Eacute;S");
			$('cart_icon').flash('0.5','1',5,'opacity',500);
		}
	}).send();
}

function removeFromCart(id, type) {
	if (type == 'frenchie') {
		id = frenchieReplace(id);
	}
	var updateCart = new Request({
		url: '../_ajax/cart.php',
		data: 'action=remove&id='+id+'&type='+type,
		async: true,
		onSuccess: function() {
			var qty = parseInt($('cart_item_'+type+id+'_qty').get('html'));
			$('cart_item_'+type+id).dispose();
			$('cart_items_qty').set('html', parseInt($('cart_items_qty').get('html'))-qty + " ITEMS<br/>S&Eacute;LECTIONN&Eacute;S");
		}
	}).send();
}

function frenchieReplace(str) {
	str = str.replace(/\?/g,"");
	str = str.replace(/=/g,"");
	str = str.replace(/&/g,"_");
	return str;
}

function setShippingCountry(cID) {
	if (cID != "") {
		location.href='../acheter/?set_shipping_country='+cID;
	}
}

// Used to communicate with Flash Object
function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

function addBikeToCart() {
	if(getFlashMovie("atomApplication").requestCodeFromActionscript) {
     getFlashMovie("atomApplication").requestCodeFromActionscript();
	} else {
		alert('Veuillez patienter pendant le téléchargemeny de l\'application.');
	}
}

function sendCodeToJS(bikeCode) {
	addToCart(bikeCode, 'Frenchie', '1150,00', 'frenchie');
}

function shareSocial(network, str) {
	
	var winName = Math.round(9999*Math.random()) + new Date().getTime();
	var winNew = false;
	var pageUrl = false;
		
	// EMAIL
	if (network == 'email') {
		parent.location='mailto:?subject='+encodeURIComponent('Check out my custom bike at AtomBicycles.com')+'&body='+encodeURIComponent('http://www.atombicycles.com/customize/'+str)
	
	// FACEBOOK
	} else if (network == 'facebook') {
		pageUrl = 'http://www.facebook.com/share.php?u='+encodeURIComponent('http://www.atombicycles.com/customize/'+str);
		winNew = window.open(pageUrl,winName,"scrollbars=1,toolbar=no,width=960,height=600");

		if(!winNew) {
				getFlashMovie("atomApplication").openWindowFromSwf(pageUrl);
		}	else {
				winNew.focus();
		}
		
	// TWITTER
	} else if (network == 'twitter') {
		
		pageUrl = '';
		winNew = window.open(pageUrl,winName,"scrollbars=1,toolbar=no,width=960,height=600");
		
		
		var r = new Request.HTML({
			url: '../_ajax/short_url.php',
			data: 'url='+encodeURIComponent('http://www.atombicycles.com/personnalise/'+str),
			onComplete: function(resultnode, resultEl, resultHtml) {
				pageUrl = 'http://twitter.com/home?status=Check+out+my+bike+at+AtomBicycles.com:+'+resultHtml;
				if(!winNew) {
						getFlashMovie("atomApplication").openWindowFromSwf(pageUrl);
				}	else {
						winNew.location.href = pageUrl;
						winNew.focus();
				}
			},
			onFailure: function() {
				pageUrl = 'http://twitter.com/home?status=Check+out+my+bike+at+AtomBicycles.com:+http://www.atombicycles.com/personnalise/'+str;
				if(!winNew) {
						getFlashMovie("atomApplication").openWindowFromSwf(pageUrl);
				}	else {
						winNew.location.href = pageUrl;
						winNew.focus();
				}
			}
		}).get();
		
	// MYSPACE
	} else if (network == 'myspace') {
		pageUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?t='+encodeURIComponent('Check out my custom bike at AtomBicycles.com')+'&u='+encodeURIComponent('http://www.atombicycles.com/personnalise/'+str);
		winNew = window.open(pageUrl,winName,"scrollbars=1,toolbar=no,width=960,height=600");

		if(!winNew) {
				getFlashMovie("atomApplication").openWindowFromSwf(pageUrl);
		}	else {
				winNew.focus();
		}
	
	// DELICIOUS
	} else if (network == 'delicious') {
		pageUrl = 'http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent('http://www.atombicycles.com/personnalise/'+str)+'&amp;title='+encodeURIComponent('Check out my custom bike at AtomBicycles.com');
		winNew = window.open(pageUrl,winName,"toolbar=no,width=550,height=550");

		if(!winNew) {
				getFlashMovie("atomApplication").openWindowFromSwf(pageUrl);
		}	else {
				winNew.focus();
		}
	}
	
}

/* 
	ACCESSORIES & COMPONENTS 
*/
function changePage(dir) {
	if (dir == 'previous') {
		if (currentPage > 1) {
			if (currentPage == totalPages) {
				new Fx.Morph($('movenext').getFirst()).start({'opacity': 1});
			}
			currentPage = currentPage-1;
			if (currentPage == 1) {
				new Fx.Morph($('moveprevious').getFirst()).start({'opacity': 0.2});
			}
			sendRequest();
		}
	} else if (dir == 'next') {
		if (currentPage < totalPages) {
			if (currentPage == 1) {
				new Fx.Morph($('moveprevious').getFirst()).start({'opacity': 1});
			}
			currentPage = currentPage+1;
			if (currentPage == totalPages) {
				new Fx.Morph($('movenext').getFirst()).start({'opacity': 0.2});
			}
			sendRequest();
		}
	} else if (dir == 'toStart') {
		new Fx.Morph($('moveprevious').getFirst()).start({'opacity': 0.2});
		if (totalResults <= resultsPerPage) {
			new Fx.Morph($('movenext').getFirst()).start({'opacity': 0.2});
		} else {
			new Fx.Morph($('movenext').getFirst()).start({'opacity': 1});
		}
	}
}

function changeCategory(newCategory) {
	$$('.parts').each(function(el,i) {
		el.removeEvents();											 
	});
	
	if (newCategory != currentCategory) {
		$('category_'+currentCategory).addClass('roll');
		$('category_'+currentCategory).set('src', $('category_'+currentCategory).get('src').replace('_selected.','_off.'));
		categoryChange = true;
		currentCategory = newCategory;
		currentPage = 1;
		$('category_'+currentCategory).removeClass('roll');
		$('category_'+currentCategory).set('src', $('category_'+currentCategory).get('src').replace('_on.','_selected.'));
	}
	sendRequest();
}

function sendRequest() {
	var r = new Request.JSON({
		url: '../_ajax/'+currentSection+'_json_f.php',
		method: 'post',
		data: 'currentCategory='+currentCategory+'&currentPage='+currentPage,
		onComplete: function(result) {
			totalResults = result.totalResults;
			totalPages = Math.ceil(totalResults/resultsPerPage);
			if (categoryChange == true) {
				categoryChange = false;
				changePage('toStart');
			}
			$("parts_wrapper").set('html', result.currentResults);
			partsComplete();
		}
	}).send();
}

function partsInit() {
	if (currentCategory != "") {
		$('category_'+currentCategory).removeClass('roll');
		$('category_'+currentCategory).set('src', $('category_'+currentCategory).get('src').replace('_off.','_selected.'));
		
		if (currentPage == 1) {
			new Fx.Morph($('moveprevious').getFirst()).start({'opacity': 0.2});
			if (currentPage == 1 && totalResults <= resultsPerPage) {
				new Fx.Morph($('movenext').getFirst()).start({'opacity': 0.2});
			}
		}
		partsComplete();
	}
}

function partsComplete() {
	// TOOLTIPS
	$$('.partsTooltip').setStyles({
		opacity: 0,
		display: 'none'
	});
	//put the effect in place
	$$('.parts').each(function(el,i) {
		el.addEvents({
			'mouseover': function() {
				el.getElement('.partsTooltip').setStyle('display', 'block');
				el.getElement('.partsTooltip').fade('in');
			},
			'mouseout': function() {
				el.getElement('.partsTooltip').fade('hide');
				el.getElement('.partsTooltip').setStyle('display', 'none');
			}
		});
	});
	Shadowbox.init({ skipSetup: true }); Shadowbox.setup(); 
}

Element.implement({
	flash: function(to,from,reps,prop,dur) {
		
		//defaults
		if(!reps) { reps = 1; }
		if(!prop) { prop = 'background-color'; }
		if(!dur) { dur = 250; }
		
		//create effect
		var effect = new Fx.Tween(this, {
				duration: dur,
				link: 'chain'
			})
		
		//do it!
		for(x = 1; x <= reps; x++)
		{
			effect.start(prop,from,to).start(prop,to,from);
		}
	}
});