/**
 * Librairie javascript commune a tout l'ecog
 *
 * @author			Julie Tetard <julie@2jstudio.com> 
 * @version		E-cog 3.0
 * @package			public
 * @subpackage		param
 * @category		js
 * @internal		last modified
 */



/**
 * Attache Evenements
 */
$(document).ready(function () {
	
	// General
	$('#shopping-cart').bind('mouseover', function() { $(this).animate({opacity: 0.5}, 300); } );
	$('#shopping-cart').bind('mouseout', function() { $(this).animate({opacity: 1}, 300); } );
	// Index
	if ($('#index')) {
		$('#wait').attr('class', 'hidden');
		$('#wait').fadeIn(2000);
		$('#welcome').attr('class', 'hidden');
		$('#welcome').fadeIn(2000);		
		var href =	$('#welcome').parent().attr('href');
		$('#welcome').parent().removeAttr('href');
		$('#welcome,#japan').bind('click', function() { 
											$('#welcome').fadeOut(1000, function() { 
																			window.location.href = ECOG_makeFullUrl(href); }); })
	}
	// Menu
	if ($('.fade').length > 0) {
		
		$('.fade').addClass('hidden');
		$('.fade').fadeIn(1500);
		//$('#inside').effect("pulsate", { times:2 }, 450);

		if (typeof(ie6) == 'undefined' || !ie6) {
			$('#navigation li').each(function(){
				$(this).bind('mouseover', function(){
					$(this).animate({
						opacity: ($(this).attr('id') == 'online-store' ? 0.3 : 0.6)
					}, 300);
				});
				$(this).bind('mouseout', function(){
					$(this).animate({
						opacity: 1
					}, 300);
				});
				
				var href = $(this).find('a').attr('href');
				$(this).find('a').removeAttr('href');
				$(this).find('a').bind('click', function(){
					$('#content').fadeOut(700, function(){
						window.location.href = ECOG_makeFullUrl(href);
					});
				})
				
				
			});
		}
		
		
	} else {
		if (typeof(ie6) == 'undefined' || !ie6) {
			$('#navigation li').each(function(){
				$(this).bind('mouseover', function(){
					$(this).animate({
						opacity: 0.6
					}, 300);
				});
				$(this).bind('mouseout', function(){
					$(this).animate({
						opacity: 1
					}, 300);
				});
			});
		}
	}
	
	if (typeof(ie6) == 'undefined' || !ie6) {
		$('.add-cart,.more-detail,#next,#previous,.no-country,#get-back').each(function(){
			$(this).bind('mouseover', function(){
				$(this).animate({
					opacity: ($(this).attr('id') == 'online-store' ? 0.3 : 0.6)
				}, 300);
			});
			$(this).bind('mouseout', function(){
				$(this).animate({
					opacity: 1
				}, 300);
			});
		});
	}	
	
	
	$('.scroll-pane,.e_item .e_block').attr('style', '').jScrollPane({scrollbarWidth:15, scrollbarMargin:20, showArrows:false} ); 
	
	detailActivate('load');
	
	
	$('.product-link').each(function() {
	
		var href = $(this).attr('href');
		$(this).removeAttr('href');
		
		$(this).bind('click', function() {
			
			// Get id 
			var itemId = $(this).parents('li').attr('id');
			$('#product-detail').load(ECOG_makeAbsUrl('param/ajax/store_product.php'), 'itemId=' + itemId + '&PHPSESSID=' + ECOG_getSesIdBis(), 
				function(responseText, textStatus, XMLHttpRequest) {
					detailActivate('click');
				}
			);			
		});
	});
	
	$('#billing-toggle').mouseup(function() {
		if ($(this).attr('checked') === true) {
			$('#billing-information').show();
		} else {
			$('#billing-information').hide();
		}
	});
	
	$('#cart-table select').change(
		function () {
			// On recalcule le total de la ligne
			var unitPrice = cleanNum($(this).parent().prev().text());
			var qtyPrice = unitPrice * $(this).val();
			$(this).parent().next().text(formatNum(qtyPrice.toFixed(2))); 
			// On recalcule le total final
			var total = 0;
			$('#cart-table table tr').find('td:last').each(
				function () {					
					var unitPrice = cleanNum($(this).text());
					total = total + parseFloat(unitPrice);					
				}				
			);			
			$('.cTotal').text(formatNum(total.toFixed(2)));
		}
	);
	
	if ($('#pictures a').length > 0) {
		$('#pictures a').lightBox({
			imageBtnClose: 'param/pix/lightbox/close.png',
			imageBtnPrev: 'param/pix/lightbox/previous.png',
			imageBtnNext: 'param/pix/lightbox/next.png',
			imageLoading: 'param/pix/lightbox/loader.gif',
			containerResizeSpeed:800
	
		});
		
	}
	if ($('.bespoke #pictures a').length > 0) {
		fillup();
	}
	
	if ($('#cart-table .product-picture').length > 0) {
		$('#cart-table .product-picture').tooltip({
		
			// each trashcan image works as a trigger 
			tip: '#tooltip',
			cancelDefault: false,
			// custom positioning 
			
			relative: true,
			// move tooltip a little bit to the right 
			offset: [265, 90],
			effect: 'fade',
			fadeInSpeed: 600,
			fadeOutSpeed: 400,
			// do not initialize tooltips until they are used 
			lazy: false,
			
			// there is no delay when the mouse is moved away from the trigger 
			delay: 0,
			onBeforeShow: function(){
				$('#tooltip').html('<img src="' + this.getTrigger().attr('src') + '" />');
			}
		});
	}
	
	$('.no-country').click(
		function() {
			pageTracker._trackEvent('NoCountry', 'Click');
		}
	);
	
	if ($('#shipping').length > 0) {
		$('#next,#previous,.no-country').click(
			function() {
				clicked = $(this).attr('id');
			}
		);
		$('#cart-form').submit(
			function() {
				if (clicked == 'next') {
					var wrong = false;
					// Shipping
					$('#shipping .inputText,#shipping .inputTextarea').each(function(){
						if ($(this).attr('id') != 'shipping-state' && $(this).val() == '') {
							$(this).addClass('e_warn');
							if (wrong === false) {
								$(this).focus();
							}
							wrong = true;
						}
						else {
							$(this).removeClass('e_warn');
						}
					});
					if (!validation($('#shipping-email').val())) {
						$('#shipping-email').addClass('e_warn');
						if (wrong === false) {
							$('#shipping-email').focus();
						}
						wrong = true;
					} else {
						$('#shipping-email').removeClass('e_warn');
					}
					if ($('#shipping-email').val() != $('#shipping-email2').val()) {
						$('#shipping-email2').addClass('e_warn');
						if (wrong === false) {
							$('#shipping-email2').focus();
						}
						wrong = true;
					} else {
						$('#shipping-email2').removeClass('e_warn');
					}
					// Billing
					if ($('#billing-toggle').not(':checked').length > 0) {
						$('#billing .inputText,#billing .inputTextarea').each(function(){
							if ($(this).attr('id') != 'billing-state' && $(this).val() == '') {
								$(this).addClass('e_warn');
								if (wrong === false) {
									$(this).focus();
								}
								wrong = true;
							}
							else {
								$(this).removeClass('e_warn');
							}
						});
						$('#billing-email').each(function(){
							if (!validation($(this).val())) {
								$(this).addClass('e_warn');
								if (wrong === false) {
									$(this).focus();
								}
								wrong = true;
							}
							else {
								$(this).removeClass('e_warn');
							}
						});
					}
					if ($('#billing-email').val() != $('#billing-email2').val()) {
						$('#billing-email2').addClass('e_warn');
						if (wrong === false) {
							$('#billing-email2').focus();
						}
						wrong = true;
					} else {
						$('#billing-email2').removeClass('e_warn');
					}
					// If false
					if (wrong === true) {
						$('#side').addClass('e_warn');
						return false;
					}
					else {
						$('#side').removeClass('e_warn');
						return true;
					}
				}				
			}
		);
	}
	
	if ($('#check-terms').length > 0) {
		$('#next,#previous,#no-country').click(
			function() {
				clicked = $(this).attr('id');
			}
		);
		$('#cart-form').submit(
			function(){
				if ($('#check-terms').not(':checked').length > 0) {
					if (clicked == 'next') {
						alert('Your must accept Crazy Pig Designs Terms & Conditions to proceed to checkout.');
						return false;
					}
				}
			} 
		);
	}
	
	

	$('#content').css('visibility','visible');
});	


function cleanNum(number) {
	var allowedH = ['0','1','2','3','4','5','6','7','8','9','.'];
	var newnumber = '';
	for (i = 0 ; i < number.length ; i++) {
		for (j = 0; j < allowedH.length; j++) {
			if (number.substr(i, 1) == allowedH[j]) {
				newnumber += number.substr(i, 1);
				break;
			}
		}
	}
	return newnumber;
}

function formatNum(number) {
	var numberH = number.toString().split('.');
	var newnumber = numberH[0]; 
	var newnewnumber = '';
	for (i = 1 ; i <= newnumber.length ; i++) {
		var j = newnumber.length - i;
		newnewnumber = (i / 3 == Math.round(i / 3) ? ' ' : '') + newnumber.substr(j, 1) + newnewnumber;
	}
	return '\u00a3 ' + newnewnumber + number.substr(number.length - 3);
}



function detailActivate(mode) {
	if ($('#product-detail').html() != '') {
	
		if (window['pgnActive']) {
			pgnActive($('#product-detail'));
		}
		var maxlen = 20;
		if ($('#detail-information table').length > 0) {
			if ($('#detail-detail').length > 0 && $('#detail-name').text().length > maxlen) {
				$('#detail-information').attr('class', 'veryhigh');
			}
			else 
				if (($('#detail-detail').length > 0 || $('#detail-name').text().length > maxlen)) {
					$('#detail-information').attr('class', 'high');
				}
		} else {
			if (($('#detail-detail').length > 0 && $('#detail-name').text().length > maxlen) || 
				(($('#detail-detail').length > 0 || $('#detail-name').text().length > maxlen)
						&& $('#detail-colors').length > 0)) {
					$('#detail-information').attr('class', 'high');
				}
		}
		
		$('#detail-size-unit').change(function(){
			var sizeType = $(this).val();
			jQuery.each(Array('uk', 'us', 'japan', 'circdiam'), function(){
				if (sizeType != this) {
					$('#tmp-sizes-' + this).hide();
				} else {
					$('#tmp-sizes-' + this).show();
				}
			})
		});
		
		$('#detail-size-unit,#tmp-sizes-uk,#tmp-sizes-us,#tmp-sizes-japan,#tmp-sizes-circdiam').change(
			function() {
				var unit = $('#detail-size-unit').val();
				var size = $('#tmp-sizes-' + unit).val();
				/*
				 * Taille Z  UK correspond a
					USA .12.5
					JAPAN. 28
					Circ. 29mm. 69mm */
				if ((unit == 'uk' && size >= 'Z') || (unit == 'us' && parseFloat(size) >= 12.5) || (unit == 'japan' && size >= '28') || 
						(unit == 'circdiam' && size > '22')) {
					if ($('#detail-size-xl').length == 0) {
						$('#tmp-sizes-circdiam').after('<p id="detail-size-xl">Attention ! <br />There\'s an additional £25 for this size.<input type="hidden" name="detail-xlfee" value="25" /></p>');
					}
				} else {
					$('#detail-size-xl').remove();
				}
			}
		);
		
		$('#detail-add-cart').replaceWith('<img id="detail-add-cart" name="detail-add-cart" src="' +  $('#detail-add-cart').attr('src') + '">');
		
		$('#detail-back').parent('a').removeAttr('href');
		
		if (mode == 'load') {
			$('#detail-back').click(function(){
				$('#product-detail').fadeOut(500);
			});
			$('#detail-add-cart').click(function(){
				$('#product-detail').fadeOut(500, addToCartConfirm);
			});
			
		} else {			
			$('#detail-back').click(function(){
				$.modal.close();
			});
			
			$('#detail-add-cart').click(function(){
				$('#add-cart-confirm').addClass('todo');
				$.modal.close();
			});
			
			$('#product-detail').modal({
				closeHTML: "",
				overlayId: 'product-overlay',
				containerId: 'product-container',
				close: true,
				overlayClose: true,
				onOpen: function(dialog){
					dialog.overlay.fadeIn(200);
					dialog.container.fadeIn(500);
					dialog.data.fadeIn(500, function(dialog){
						$(dialog).find('#detail-picture').fadeIn(800);
						$(dialog).find('#detail-loader').fadeOut(1000);
					});
				},
				onClose: function(dialog){
					dialog.overlay.fadeOut(500);
					$('#detail-picture').fadeOut(100, function(){
						dialog.container.fadeOut(500, function(){
							if ($('#add-cart-confirm.todo').length > 0) {
								addToCartConfirm();
							} else {
								$('#product-detail').html('');
								$.modal.close();
							}
							
						});
					});
				}
			});
		}
		
		$('.add-cart,#detail-add-cart,#detail-back,#detail-shopping-cart').each(function(){
			$(this).bind('mouseover', function(){
				$(this).animate({
					opacity: ($(this).attr('id') == 'online-store' ? 0.3 : 0.6)
				}, 300);
			});
			$(this).bind('mouseout', function(){
				$(this).animate({
					opacity: 1
				}, 300);
			});
		});
	}
	
}

function validation(email)
{
	var verif = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 	 if (verif.exec(email) == null)	{
		return false;
	} else	{
		return true;
	}
} 

function addToCartConfirm() {
	$('#add-cart-confirm').html('The product <strong>' + $('#detail-name').text() + '</strong> has been added to your cart.');
	
	
	// Validation Ajax du formulaire
	$('#detail-form').attr('action', 'param/ajax/addToCart.php?PHPSESSID=' + ECOG_getSesIdBis());
	$('#detail-form').ajaxSubmit({
		// >> Succes : update
		success: function(data) {
			$.modal.close();
			// Ts cas : on supprime le loader + select des soeurs
			$('#shopping-cart').html('<img alt="Shopping Cart" src="param/pix/shared/shopping-cart.png"/>' + data);
			$('#product-detail').html('');
			$('#add-cart-confirm').removeClass('todo');
			$('#add-cart-confirm').modal({
				closeHTML: "",
				overlayId: 'confirm-overlay',
				containerId: 'confirm-container',
				close:true,
				overlayClose:true ,
				onOpen: function (dialog) {
					dialog.overlay.fadeIn(500);
					dialog.container.fadeIn(500);
					dialog.data.fadeIn(500);
				},
				onClose: function (dialog) {
					dialog.overlay.fadeOut(500);
					dialog.container.fadeOut(500, function () {
						$.modal.close();
					});
				}
			});
			setTimeout(function() { $.modal.close(); }, 1300);	
		}
	});
	
	
	
}



/***********************************************
* CMotion Image Gallery- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for source code
* This copyright notice must stay intact for legal use
* Modified for autowidth and optional starting positions in
* http://www.dynamicdrive.com/forums/showthread.php?t=11839 by jschuer1 8/5/06
***********************************************/

 //1) Set width of the "neutral" area in the center of the gallery.
var restarea=6;
 //2) Set top scroll speed in pixels. Script auto creates a range from 0 to top speed.
var maxspeed=6;
 //3) Set to maximum width for gallery - must be less than the actual length of the image train.
var maxwidth=840;
 //4) Set to 1 for left start, 0 for right, 2 for center.
var startpos=0;
 //5) Set message to show at end of gallery. Enter "" to disable message.
var endofgallerymsg='';

function enlargeimage(path, optWidth, optHeight){ //function to enlarge image. Change as desired.
var actualWidth=typeof optWidth!="undefined" ? optWidth : "600px" //set 600px to default width
var actualHeight=typeof optHeight!="undefined" ? optHeight : "500px" //set 500px to  default height
var winattributes="width="+actualWidth+",height="+actualHeight+",resizable=yes"
window.open(path,"", winattributes)
}

////NO NEED TO EDIT BELOW THIS LINE////////////

var iedom=document.all||document.getElementById, scrollspeed=0, movestate='', actualwidth='', cross_scroll, ns_scroll, statusdiv, loadedyes=0, lefttime, righttime;

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function creatediv(){
statusdiv=document.createElement("div")
statusdiv.setAttribute("id","statusdiv")
document.body.appendChild(statusdiv)
statusdiv=document.getElementById("statusdiv")
statusdiv.innerHTML=endofgallerymsg
}

function positiondiv(){
var mainobjoffset=getposOffset(crossmain, "left"),
menuheight=parseInt(crossmain.offsetHeight),
mainobjoffsetH=getposOffset(crossmain, "top");
statusdiv.style.left=mainobjoffset+(menuwidth/2)-(statusdiv.offsetWidth/2)+"px";
statusdiv.style.top=menuheight+mainobjoffsetH+"px";
}

function showhidediv(what){
if (endofgallerymsg!="") {
positiondiv();
statusdiv.style.visibility=what;
}
}

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft: what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}


function moveleft(){
if (loadedyes){
movestate="left";
if (iedom&&parseInt(cross_scroll.style.left)>(menuwidth-actualwidth)){
cross_scroll.style.left=parseInt(cross_scroll.style.left)-scrollspeed+"px";
showhidediv("hidden");
}
else
showhidediv("visible");
}
lefttime=setTimeout("moveleft()",10);
}

function moveright(){
if (loadedyes){
movestate="right";
if (iedom&&parseInt(cross_scroll.style.left)<0){
cross_scroll.style.left=parseInt(cross_scroll.style.left)+scrollspeed+"px";
showhidediv("hidden");
}
else
showhidediv("visible");
}
righttime=setTimeout("moveright()",10);
}

function motionengine(e){
var mainobjoffset=getposOffset(crossmain, "left"),
dsocx=(window.pageXOffset)? pageXOffset: ietruebody().scrollLeft,
dsocy=(window.pageYOffset)? pageYOffset : ietruebody().scrollTop,
curposy=window.event? event.clientX : e.clientX? e.clientX: "";
curposy-=mainobjoffset-dsocx;
var leftbound=(menuwidth-restarea)/2;
var rightbound=(menuwidth+restarea)/2;
if (curposy>rightbound){
scrollspeed=(curposy-rightbound)/((menuwidth-restarea)/2) * maxspeed;
clearTimeout(righttime);
if (movestate!="left") moveleft();
}
else if (curposy<leftbound){
scrollspeed=(leftbound-curposy)/((menuwidth-restarea)/2) * maxspeed;
clearTimeout(lefttime);
if (movestate!="right") moveright();
}
else
scrollspeed=0;
}


function contains_ns6(a, b) {
if (b!==null)
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function stopmotion(e){
if (!window.opera||(window.opera&&e.relatedTarget!==null))
if ((window.event&&!crossmain.contains(event.toElement)) || (e && e.currentTarget && e.currentTarget!= e.relatedTarget && !contains_ns6(e.currentTarget, e.relatedTarget))){
clearTimeout(lefttime);
clearTimeout(righttime);
movestate="";
}
}

function fillup(){
if (iedom){
crossmain=document.getElementById? document.getElementById("motioncontainer") : document.all.motioncontainer;
if(typeof crossmain.style.maxWidth!=='undefined')
crossmain.style.maxWidth=maxwidth+'px';
menuwidth=crossmain.offsetWidth;
cross_scroll=document.getElementById? document.getElementById("motiongallery") : document.all.motiongallery;
actualwidth=document.getElementById? document.getElementById("trueContainer").offsetWidth : document.all['trueContainer'].offsetWidth;
if (startpos)
cross_scroll.style.left=(menuwidth-actualwidth)/startpos+'px';
crossmain.onmousemove=function(e){
motionengine(e);
}

crossmain.onmouseout=function(e){
stopmotion(e);
showhidediv("hidden");
}
}
loadedyes=1
if (endofgallerymsg!=""){
creatediv();
positiondiv();
}
if (document.body.filters)
onresize()
}


onresize=function(){
if (typeof motioncontainer!=='undefined'&&motioncontainer.filters){
motioncontainer.style.width="0";
motioncontainer.style.width="";
motioncontainer.style.width=Math.min(motioncontainer.offsetWidth, maxwidth)+'px';
}
menuwidth=crossmain.offsetWidth;
cross_scroll.style.left=startpos? (menuwidth-actualwidth)/startpos+'px' : 0;
}