//globals
var disable = {
	'eachProdZoom' : false
};

//setup configuration params
var baseURL;

/*
 * Ensure that JS is unobstructive and navigation is possible
 */
$(function(){

	//init
	$('#menuTop').removeClass('mTop_jsUnobst');
	$('.hasChildCat').removeClass('hCC_jsUnobst');
	$('._submenu ._xClose').css('display','block');

});

$(function(){
	var ambiente = 'development';
	var pais = 'portugal';
	var confFilePath;
	if( window.location.hostname.indexOf('pixel.pt') > 0 )
	{
		confFilePath = 'http://www.pixel.pt/clientes/conforama/v2/public/xml/configuration.xml';
	}
	else if ( window.location.hostname.indexOf('conforama') > 0 )
	{
		ambiente = 'tests';
		if(window.location.href.indexOf('conforama.es/v2/')>0)
		{
			confFilePath = '/v2/public/xml/configuration.xml';
			pais = 'espana';
		}
		else if(window.location.href.indexOf('conforama.pt/v2/')>0)
		{
			confFilePath = '/v2/public/xml/configuration.xml';
			pais = 'portugal';
		}
		else if(window.location.href.indexOf('conforama.es/v3/')>0)
		{
			confFilePath = '/v3/public/xml/configuration.xml';
			pais = 'espana';
		}
		else if(window.location.href.indexOf('conforama.pt/v3/')>0)
		{
			confFilePath = '/v3/public/xml/configuration.xml';
			pais = 'portugal';
		}		
		else
		{
			ambiente = 'production';
			confFilePath = '/public/xml/configuration.xml';
		}	
	}
	else{
		confFilePath = '/conforama/v2/public/xml/configuration.xml';
	}
	
	//Setup baseURL
	$.ajax({
	  type: 'GET',
	  url: confFilePath,
	  dataType: 'xml',
	  success: function(xml) {
		
		switch(ambiente)
		{
		case 'tests':
			baseURL = $(xml).find(ambiente).find(pais).find('baseURL').text();
			break;
		case 'production':
			baseURL = $(xml).find(ambiente).find('url').find('baseURL').text();
			break;
		default: //development
			baseURL = $(xml).find(ambiente).find('url').find('baseURL').text();
		}
		
	  }
	});

});

// place data on content area based on id #content
var getContent = function(data){
			$("#content").html( $(data).find("#content").html() );
};

//splashscreen action
var showSplashScreen = function(param){
	if (param)
	{
		$('#splashScreen').removeClass('hidden');
		$('#rootBackDarkBox').removeClass('hidden');
	}
	else
	{
		$('#splashScreen').addClass('hidden');
		$('#rootBackDarkBox').addClass('hidden');
	};
};

// we're showing splashscreen only if there's JS
// non obstructive js principle
$(function(){
	var state = $('#splashScreen input.splashscreen_state').val() == 1 ? true : false;
	showSplashScreen(state);
});

$('#splashScreen').live({
	click: function(el){
		
		if($(el.currentTarget).find('a').attr('href').indexOf('#') > -1)
		{
			el.preventDefault();
		}
		
		//bool
		var useURL = $(this).find('input[name="useURL"]').val();
		var curURL = $(el.currentTarget).attr('href');
		
		showSplashScreen(false);
		
		useURL === 1 ? window.location = curURL : false;
		
	}
});

//reset menu
var resetMenu = function(){

	$('#menuTop li').attr('style','');
	
	$('._btnBorderCut').css('display','none');
	//$('#backDarkBox').css('display','none');
	$('#backDarkBox').addClass('hidden');
	$('._submenu').css('display','none');
	
	$('#menuTopHeader').css('z-index','');
	$('#menuTop').css('z-index','');
		
}; //end reset

//Menu action to open submenu
$('#menuTop li ._btnShape').live({

	click : function(){

		resetMenu();
		
		var curLi = $(this).parent('li');
		
		$('#menuTopHeader').css('z-index','0');
		$('#menuTop').css('z-index','30');
		
		
		if ( $(curLi).attr('class').indexOf('pink') > 0 )
		{
			$(curLi).css('background-position','-20px -270px');
		}
		else if (  $(curLi).attr('class').indexOf('sea') > 0  )
		{
			$(curLi).css('background-position','-20px -180px');
		}
		else if ( $(curLi).attr('class').indexOf('blue') > 0 )
		{
			$(curLi).css('background-position','-20px -150px');
		}
		else if ( $(curLi).attr('class').indexOf('imgBorderRight') > 0 && $(curLi).attr('class').indexOf('darkgrey') > 0 )
		{
			$(curLi).css('background-position','right -210px');
		}
		else if ( $(curLi).attr('class').indexOf('imgBorderLeft') > 0 && $(curLi).attr('class').indexOf('orange') > 0 )
		{
			$(curLi).css('background-position','left -90px');		
		}
		else if (  $(curLi).attr('class').indexOf('orange') > 0  )
		{
			$(curLi).css('background-position','-20px -90px');		
		}
		else if (  $(curLi).attr('class').indexOf('red') > 0  )
		{
			$(curLi).css('background-position','-20px -473px');		
		}		
		else
		{		
			$(curLi).css('background-position','-20px -36px');		
		}
		
		
		$(curLi).find('._btnBorderCut').css('display','block');
		//$('#backDarkBox').css('display','block');
		$('#backDarkBox').removeClass('hidden');
		$(curLi).find('._submenu').css('display','block');
	}

});

//Menu action to close submenu
$('._xClose').live({
	
	click: function(){
		
		var curSubMenu = $(this).parent('._submenu');
		var btnBorderCut = $(curSubMenu).prev('._btnBorderCut');
		
		resetMenu();

	}

});

//backdrop action
$('#backDarkBox').live({
		
		click : function(){

			resetMenu();

		}
		
});

//menu item sublists action
$('.hasChildCat').live({
	click : function(){
	
		var reset = function(){
			$('.hasChildCat ul').css('display','none');
			$('.hasChildCat .hasArrow').attr('class','hasArrow seta');	
		}; //reset
		
		var state = $(this).find('ul').css('display');
		var arrowEl = $(this).find('span.hasArrow');
		
		if ( state === 'none' )
		{
			reset();
			$(arrowEl).attr('class','hasArrow arrowDown');
			$(this).find('ul').css('display','block');
		}
		else
		{
			reset();
			$(arrowEl).attr('class','hasArrow seta');
			$(this).find('ul').css('display','none');
		}
	}
});

//zoom eachProd action
var resetItemProdEach = function(){
	$('#rootBackDarkBox').addClass('hidden');
	$('.hiddenProdZoom').addClass('hidden');
	$('.item_prod_each_rec').css('z-index','');
	$('.hiddenProdZoom').css('z-index','');
};
var clearZoomProd = function(){
		$('.hiddenProdZoom').addClass('hidden');		
};

if ( ! $.browser.msie || ($.browser.version && $.browser.version > 7) )
{
	$('.item_prod_each_rec').live({
		mouseover : function(){

			//Expand eachItemProd box, if not in gallery
			if ( ! $(this).parents('.prodScreen').length > 0 && disable.eachProdZoom == false )
			{
				resetItemProdEach();
				$('#rootBackDarkBox').removeClass('hidden');
				$(this).find('.hiddenProdZoom').removeClass('hidden');
				$(this).css('z-index',4);
				$(this).find('.hiddenProdZoom').css('z-index',5);				
			}			
		},
		mouseout : function(){
		
			if ( ! $(this).parents('.prodScreen').length > 0  && disable.eachProdZoom == false )
			{
				resetItemProdEach();
			}
			
		}

	});
}

//increment cart item action
var incEachProdRawTotal = function(el)
{
	var priceCntainer = $(el.currentTarget).parents('.eachProdRawLine').find('.tdPriceEachTotal .ttP');

	var qnt = $(el.currentTarget).parents('form').find('._qntWrp input[name=quantity]').val();
	var price = $(el.currentTarget).parents('.eachProdRawLine').find('.tdPrice .snglP').text();
	var total = qnt * (parseFloat(price).toFixed(2));

	priceCntainer.text(total.toFixed(2)) ? incProdRawsTotal(el) : null;
}
var incProdRawsTotal = function(el)
{
	var allTotalPrices = $(el.currentTarget).parents('#tabLivraison').find('.tdPriceEachTotal .ttP');

	var total = 0;
	$.each(allTotalPrices, function(k, v){
		total += parseFloat($(v).text());
	});

	$('#totalOrderPrice .tOP').text(total.toFixed(2));
	
	// update topCartList for handling only in checkoutCart case
	var isCartCheckout = $(el.currentTarget).parents('form.eachCartFrom').find('input[name=isCartCheckout]').val();
	isCartCheckout == 1 ? getCartAjaxRunner(el) : null;
	
}
var incOrderProdQuantity = function(el)
{
		var prntForm = $(el.currentTarget).parents('form');
		var elQuantity = prntForm.find('._qntWrp input[name=quantity]');
		var handle = $(el.currentTarget).attr('class').indexOf('handlerLess') > 0 ? 'less' : 'more';
		var total = elQuantity.val();
		total = parseInt(total);

		if ( handle === 'less' )
		{
			total = total > 1 ? total - 1 : total;
			elQuantity.val(total) ? incEachProdRawTotal(el) : null;
		}
		else
		{
			total = total + 1;
			elQuantity.val(total) ? incEachProdRawTotal(el) : null;
		}
};
$('.handlers').live({
	click : function(el){
		incOrderProdQuantity(el);
	}
});

//zoom product image
var resetMagnifyProdIndex = function(state){
		
		if ( state === 'open' )
		{
			/* start: fix to ie7 */
			$('#menuTop').css('z-index',0);
			$('#singleProductWrp').css('z-index',3);
			$('.column_iSingle_a').css('z-index',2);
			$('#magnifyProd').css('z-index',999);
			/* end: fix to ie7 */
		}
		else if ( state === 'close' )
		{
			$('#menuTop').css('z-index','');
			$('#singleProductWrp').css('z-index','');
			$('.column_iSingle_a').css('z-index','');
			$('#magnifyProd').css('z-index','');
			/* end: fix to ie7 */
		}
		
};

var openCloseMagnify = function(state){

	if ($.browser.msie ) {

		if ( state === 'open' )
		{
			$('#magnifyProd').css('opacity',0); /* important, to chain animate and fadeIn */
			$('#magnifyProd').animate({
				'width' : 650,
				'top' : -85,
				'left' : 145,
				'opacity': 1,
				'padding-bottom': 15
			}, 1500);
			
			/*
			$('#backProdMagnifyDarkBox').css('display','block');
			$('#magnifyProd').css('display','block');
			*/
			$('#backProdMagnifyDarkBox').removeClass('hidden');
			$('#magnifyProd').removeClass('hidden');
		}
		else if ( state === 'close' )
		{

			$('#magnifyProd').animate({
				'width' : 455,
				'top' : 0,
				'left' : 0,
				'opacity': 0
			}, 850, function(){
					//$('#magnifyProd').css('display','none');
					$('#magnifyProd').addClass('hidden');
			});

			//$('#backProdMagnifyDarkBox').css('display','none');
			$('#backProdMagnifyDarkBox').addClass('hidden');
		
		}//end OpenClose
	
	}
	else {

		if ( state === 'open' )
			{
			$('#magnifyProd').css('opacity',0); /* important, to chain animate and fadeIn */
			$('#magnifyProd').animate({
				'width' : 650,
				'top' : -85,
				'left' : 145,
				'opacity': 1,
				'position': 'absolute',
				'padding-bottom': 15				
			}, 1500);

			$('#backProdMagnifyDarkBox').removeClass('hidden');
			$('#magnifyProd').removeClass('hidden');
		
		}
		else if ( state === 'close' )
		{

			$('#magnifyProd').animate({
				'width' : 455,
				'top' : 0,
				'left' : 0,
				'opacity': 0,
				'position': 'absolute'
			}, 850, function(){
					//$('#magnifyProd').css('display','none');
					$('#magnifyProd').addClass('hidden');
			});

			//$('#backProdMagnifyDarkBox').css('display','none');
			$('#backProdMagnifyDarkBox').addClass('hidden');
			
		}//end OpenClose
	}; //if ie
};

$('.column_iSingle_a #img_iSingle').live({
	click : function(){
		
		resetMagnifyProdIndex('open');
		
		openCloseMagnify('open');	
	}
});

$('#zoomProd').live({
	click : function(){
		
		resetMagnifyProdIndex('open');
		
		openCloseMagnify('open');
	},
	mouseover : function(){
		$('#img_iSingle span._iconZoomI').css('display','inline-block');
		$('#img_iSingle span._iconZoomI').addClass('_icon_zoom');
	},
	mouseout : function(){
		$('#img_iSingle span._iconZoomI').css('display','');
		$('#img_iSingle span._iconZoomI').removeClass('_icon_zoom');
	}
});

$('#magnifyProd ._xClose').live({
	click : function(){
	
		openCloseMagnify('close');
			
		resetMagnifyProdIndex('close');
		
	}
});

//add to cart action
var getCartTotal = function(){
	$.post( baseURL+'index.php/orders/cartTotalItems', function(total){
		$('#userTotalItemsOnCart').text(total);
		loaderAnim(false);
	});
};
var replaceCartTable = function(data){
	$('#cartTable').remove();
	$('#shopCartWrp ._mid').html(data);
};
var addToCart = function(el){

		loaderAnim(true);
	
		var curEl = $('#frmCartAdd').length > 0 ? $('#frmCartAdd') : $(el.currentTarget).parents('form.eachCartFrom');
		var curUrl = curEl.attr('action') ? curEl.attr('action') : $('#frmCartAdd').attr('action');
		
		$.post( curUrl, curEl.serializeArray(), function(data) {
			replaceCartTable(data);
			getCartTotal();
		});		
};
var getCartAjaxRunner = function(el){

	var ref = $(el.currentTarget).parent('form').find('input[name="reference"]').val();
	var qnt = $(el.currentTarget).parent('form').find('input[name="quantity"]').val();
	
	$(el.currentTarget).parent('form').find('input[name="getCartAjax"]').val(1);
	
	el.preventDefault();
	addToCart(el);
}
// add to cart ajaxa function
$(function(){
	
	//default action for each Signle Add to Cart Prod btnSumbt
	$('body').delegate('#frmCartAdd', 'submit', function(e){
		$('.getCartAjax').val(1); /* by default we wont use ajax so we need to set it */
		getCartAjaxRunner(e);
	});
		
});


//form costumer support action
$('#cSupportWrap form div.eachInput .colLeft ul li input').live({
	click : function(){
		$('#interestArea').css('display','block');
	}
});

$('#cSupportWrap form div.eachInput .colRight ul li input').live({
	click : function(){
		$('#interestArea').css('display','none');
	}
});

$('.rulesWrp .chk').live({
	click : function(){

		$(this).is(':checked') ? $('#sbmt_cSupport').css('display','block') : $('#sbmt_cSupport').css('display','none');
	}
});

//galleryCarousel action
var gallery = function(className,setDelay, setNumVisible){
	
	var delay = setDelay;
	var curProdIndex = 1;
	var stop = false; /* animation must go on before any var change */
	var blockWidth = 0;
	
	var moveGalContent = function(direction){
	
					var eachItemSize = parseInt( $(className).find('.prodScreen ul li.eachLstProd').css('width') );
					var numVisible = setNumVisible;
					var totalItems = parseInt( $(className).find('.prodScreen ul li.eachLstProd').length );
					var curPosX =  parseInt( $(className).find('.prodScreen ul.galW').css('left') );
	
					blockWidth = blockWidth ? blockWidth : $(className).find('.prodScreen ul.galW').css('width', eachItemSize * totalItems );
				
					//Prevent that the number of visible products has a gap, comparing with expected num of visible prods					
					var preventGap = function(){
						
						var z = totalItems - curProdIndex;
				
						if ( z + 1 < numVisible && direction == 'left' )
						{

							//modulus
							var mod = totalItems % curProdIndex;
							
							curProdIndex = curProdIndex - mod; //set correct index with offset
							moveThis =  moveThis + ( eachItemSize * mod);
						}
						else if ( curProdIndex == 0 && direction == 'right' )
						{

							curProdIndex = 1; //set correct index with offset
							moveThis =  0;	
						}
						
					};
					
					var animateGal = function(){

						curProdIndex = (direction == 'left' ?  curProdIndex + numVisible : curProdIndex - numVisible);
						stop = true;

						preventGap();
						
						$(className).find('.prodScreen ul.galW').animate({
							'left' : moveThis
						},1500, function(){
							stop = false;
						});

					};
		
					var resetGal = function(){

						curProdIndex = 1;
						stop = true;

						$(className).find('._hndlrs').fadeOut();
						
						//fadeOut/In each li
						var goIn = function(){
							var timer = 150;
							var xInc = 1;
							$(className).find('.prodScreen ul li.eachLstProd').each(function(index,el){

								if ( index > numVisible )
								{
									return false;
								}
								else
								{
									$(el).delay(timer*xInc++).fadeOut().fadeIn();
								};
								
							});
						}; //end goOff
						
						//default reset animation
						$(className).find('.prodScreen ul.galW').animate({
							'left' : 0
						}, ( 250 * totalItems ), function(){
							stop = false;
							$(className).find('._hndlrs').fadeIn();
							goIn();
						});
						
					};


					if ( direction == 'left' && Math.ceil( (curProdIndex + numVisible) ) < Math.ceil( totalItems ) && ! stop )
					{			
						curPosX = curPosX - (eachItemSize * numVisible)
						moveThis = curPosX;
						animateGal();
					
					}
					else if ( direction == 'right' && Math.ceil( (curProdIndex - numVisible) ) > -1 && ! stop )
					{
						curPosX = curPosX + (eachItemSize * numVisible);
						moveThis= curPosX;
						animateGal();
					}
					else if ( direction == 'left' && ! stop )
					{
						//Since we've a default animation, reverse it when reaches to end
						direction = 'right';
						resetGal();
					}


	};

	$(className).find('._hndlrs ._left').live({
		click : function(){
			moveGalContent('right');
		}
	});
	$(className).find('._hndlrs ._right').live({
		click : function(){
			moveGalContent('left');
		}
	});
	$(className).find('.prodScreen ul li.eachLstProd').live({
		mouseover : function(){
			stop = true;
		},
		mouseout : function(){
			stop = false;
		}
	});

	//default timed action
	setInterval(function(){
		moveGalContent('left');
	},delay);

};


gallery('.complementares',8250,5);
gallery('.sugestoes',12500,5);
//gallery('.homeGal',10000,3);
gallery('.wide',10200,5);
gallery('.wide2',13000,5);
gallery('.wide3',14500,5);
gallery('.wide4',9000,5);
gallery('.top_vendas',8750,5);
gallery('.promocao',11000,5);

//action for content update via ajax

var loaderAnim = function(state){
		
		if ( state )
		{
			//$('#backDarkBox').css('display','block');
			$('#backDarkBox').removeClass('hidden');
			//$('#cartLoader').css('display','block');
			$('#cartLoader').removeClass('hidden');
			$('#menuTop').css('z-index',0);
			$('#searchBox').css('z-index',0);
			$('#cartWrap').css('z-index',0);
			$('#backDarkBox').css('z-index',40);
			$('#cartLoader').css('z-index',41);
		}
		else
		{
				$('#menuTop').css('z-index','');
				$('#searchBox').css('z-index','');
				$('#cartWrap').css('z-index','');
				$('#backDarkBox').css('z-index','');
				$('#cartLoader').css('z-index','');
				
				//$('#rootBackDarkBox').css('display','none');
				$('#rootBackDarkBox').addClass('hidden');
				//$('#backDarkBox').css('display','none');
				$('#backDarkBox').addClass('hidden');
				//$('#cartLoader').css('display','none');
				$('#cartLoader').addClass('hidden');
		}

};

//remove rowTitle (if not needed) by async update
var removeCatRowTitle = function(param){
		$('#catRowHeadTitle').css('display', ( param == true ? 'block' : 'none' ) );
		$('.fakeColLeft').css('display', ( param == true ? 'block' : 'none' ) );
		$('.fakeColRight').css('display', ( param == true ? 'block' : 'none' ) );		
};

// actino for async calls / page requests
var pageRequester = function(el){
		el.preventDefault();
		
		//if linkage request came from mainMenu, close sub
		if ( $(this).parents('._submenu').css('display') == 'block' )
		{
			resetMenu();
		}; //endif mainMenuLinkage
		
		var curURL =  $(el.currentTarget).attr("href");

		resetItemProdEach();
		clearZoomProd();
		
		loaderAnim(true);
		
		disable.eachProdZoom = true;
		
		$.ajax({
			url: curURL, 
			success: function(data) {

			disable.eachProdZoom = false;
		
			setTimeout(function(){
				
							removeCatRowTitle( $(data).find("#content").attr('class') == 'hasCatRowHeadTitle' ? true : false );
							$(data).find("#content").attr('class') == 'hasCatRowHeadTitle' ? $("#content").addClass('hasCatRowHeadTitle') : null;

							$("#catRowHeadTitle").html( $(data).find("#catRowHeadTitle").html() );
							$("#content").html( $(data).find("#content").html() );
							
			},1000);
			
			setTimeout(function(){
				loaderAnim(false);
			},2500);
		  
			ocasionalScripts();
					
		  }
		});
};
$('a.asyncCall').live({
	click: function(el){
		scrollWindowUp();
		resetMenu();	
		el.preventDefault();
		pageRequester(el);
	}
});

//print action
$('.printPage a').live({
	click: function(e){
		e.preventDefault();
		window.print();
	}
});

//spot image switcher
$('#menuVerticalTop ul li').live({
	mouseover : function(){
		
		var curIndex = $('#menuVerticalTop ul li').index(this);
		var imgSz = 70;
		
		$('#iconSpot span').css('background-position', '0' + ' ' + (imgSz * curIndex) * -1 + 'px' );
	
	}
});

// Main menu, submenu mouseout action
// The point is, there's a small delay before closing the submenu
// when moving the mouse out of it!
var someDelay;
var maxTimeMouseOutSubmenu = 650;

$('#backDarkBox').live({
	mouseover : function(){

		someDelay = setTimeout(function(){
			resetMenu();
		},maxTimeMouseOutSubmenu);

	
		$.each( $('._submenu'), function( k, v) { 
		  
			if ( $( v ).css('display') === 'block' ) {
				//resetMenu();
				someDelay;
			}			

		});


	},
	mouseout : function(){
		clearTimeout(someDelay);
	}
});

// create new user action
$('.UserRegistrationUpdateForm').live({
	click : function(el){

		el.preventDefault();
		
		if ( $('#formNewUser').css('display') !== 'block' )
		{
			$('#formNewUser').css('display','block');		
		}
		else
		{
			$('#formNewUser').css('display','none');		
		}
		
	}
});

// search filters actions
$('#searchBoxFilters ._mid ._filters li').live({
	click : function(el) {

		el.preventDefault();

		if ( $(el.currentTarget).attr('class').indexOf('_1') > -1 ) {

			if ( $(el.target).parent().css('background-position') === '0px 0px' || $(el.target).parent().attr('class').indexOf('selected') > -1 )
			{
				$(el.target).parent().css('background-position','0px -38px');
				$(el.target).parent().removeClass('selected');
			}
			else
			{
		
				$(el.target).parent().css('background-position','0px 0px');			
				$(el.target).parent().addClass('selected');
			}
			
		};

		if ( $(el.currentTarget).attr('class').indexOf('_2') > -1 ) {
			
			if ( $(el.target).parent().css('background-position') === '-45px 0px' || $(el.target).parent().attr('class').indexOf('selected') > -1 )
			{
				$(el.target).parent().css('background-position','-45px -38px');
				$(el.target).parent().removeClass('selected');			
			}
			else
			{
				$(el.target).parent().css('background-position','-45px 0px');			
				$(el.target).parent().addClass('selected');			
			}
			
		};

		if ( $(el.currentTarget).attr('class').indexOf('_3') > -1 ) {
			
			if ( $(el.target).parent().css('background-position') === '-90px 0px' || $(el.target).parent().attr('class').indexOf('selected') > -1 )
			{
				$(el.target).parent().css('background-position','-90px -38px');
				$(el.target).parent().removeClass('selected');			
			}
			else
			{
				$(el.target).parent().css('background-position','-90px 0px');			
				$(el.target).parent().addClass('selected');			
			}
			
		};
	
		if ( $(el.currentTarget).attr('class').indexOf('_4') > -1 ) {
			
			if ( $(el.target).parent().css('background-position') === '-134px 0px' || $(el.target).parent().attr('class').indexOf('selected') > -1 )
			{
				$(el.target).parent().css('background-position','-134px -38px');
				$(el.target).parent().removeClass('selected');			
			}
			else
			{
				$(el.target).parent().css('background-position','-134px 0px');			
				$(el.target).parent().addClass('selected');			
			}
		
		};

		
	}
});

// search cat action
$('#searchBoxFilters ._mid ._wrp ul._cats li').live({

	click : function(el) {
	
		var catId = $(el.currentTarget).find('.value').text() ? $(el.currentTarget).find('.value').text() : null;
		var listType = $(el.currentTarget).parent().parent().parent().attr('id') ? $(el.currentTarget).parent().parent().parent().attr('id') : null;
		var curName = $(el.target).find('.name').text() ? $(el.target).find('.name').text() : ( $(el.target).parent().find('.name').text() ? $(el.target).parent().find('.name').text() : null );

		$('#searchBoxFilters .ajaxLoader').removeClass('hidden');

				
		if ( catId !== null && catId.length <= 3 )
		{
				
				$.ajax({
					url: baseURL + 'index.php/menu/getSearchCats/' + catId,
					success: function(data) {

						// for the cases the parent is switched, its childs must be updated
						// otherwise, we'll treat as childs
						if ( listType === 'parents' )
						{
							// ensure that we allways remove child parents, when switching / using parents selector
							$.each( $('#searchBoxFilters ._mid ._wrp ul._cats li .ddList'), function(k,v) {

								if ( $(v).attr('id') !== 'parents' )
								{
									$(v).remove();				  
								}
							});
							
							$(el.currentTarget).parent().parent().find('ul#parents > li > span.title').text(curName);
							
							// we'll allways append childs to parents, after all
							$(data).appendTo('#searchBoxFilters ._mid ._wrp ul._cats > li');
						}
						else
						{
							// we'll do the same as above, but we must know what's the current working index of the selector
							var curIndex = $('#searchBoxFilters ._mid ._wrp ul._cats > li .ddList.childs').index( $(el.target).parent().parent() );
							
							if ( $(el.target).parent().parent().attr('class').indexOf('childs') > -1 )
							{
								
								var nrChilds = $('#searchBoxFilters ._mid ._wrp ul._cats > li .ddList.childs').length;

								var i = 0;
								$.each( $('#searchBoxFilters ._mid ._wrp ul._cats > li .ddList.childs'), function(k,v) {
								
									// ensure that we remove specific childs that are not the current selected
									if ( $('#searchBoxFilters ._mid ._wrp ul._cats > li .ddList.childs').index( $(v) ) !== curIndex && $('#searchBoxFilters ._mid ._wrp ul._cats > li .ddList.childs').index( $(v) ) > curIndex )
									{

										$(v).remove();		
									}
								
									i++; /* increment */
								
								});

								function fnWaiter() {

									if ( i == nrChilds ) {

										clearInterval(interv);
											
										setTimeout(function() {
										
											$(data).appendTo('#searchBoxFilters ._mid ._wrp ul._cats > li');	

											setTimeout(function(){
												$('#searchBoxFilters .ajaxLoader').addClass('hidden');
											},1000);											
											
										},1000);
									
									}
									else
									{
										$('#searchBoxFilters .ajaxLoader').removeClass('hidden');
									}
								};
								
								var interv = setInterval(fnWaiter,500);
								

								$(el.target).parent().parent().find('span.title').text(curName);
								
							}
							else
							{
								$(data).appendTo('#searchBoxFilters ._mid ._wrp ul._cats > li');
							
								$(el.target).parent().parent().find('span.title').text(curName);
							
							}
							
						}

						setTimeout(function(){
							$('#searchBoxFilters .ajaxLoader').addClass('hidden');
						},1000);
						
					}
				
				});
				
		}
		else
		{
			setTimeout(function(){
				$('#searchBoxFilters .ajaxLoader').addClass('hidden');
			},1000);
		}
 
	}
	
});

// action for prices list select
$('ul._prices li ul#prices ul.listing li').live({
	click: function(el){

		$('#searchBoxFilters .ajaxLoader').removeClass('hidden');
	
		var idVal = $(el.target).find('span.value').text();
		var name = $(el.target).find('span.name').text();
		
		$(el.target).parent().parent().parent().find('li span.title').text(name);

		setTimeout(function(){
			$('#searchBoxFilters .ajaxLoader').addClass('hidden');
		},1000);
		
	}
});

// chosen plugin for better select boxes
$(document).ready(function() {

	//$(".selectClass").chosen();	
	// $("input[type='text']").clearInput();
	$('.autoClear').clearInput();
});

// form validation (newsletter subscribe)
var getNwsltrSuccess = function(){
	url = baseURL + 'index.php/newsletter/success';

	$.ajax({
	  url: url,
	  success: function(data){
		$("#content").html( $(data).find("#content").html() );				  
	  }
	});
}

$(function(){
	$('#newUserReg').submit(function(evt){
		
		// make sure that when submiting there's no error msgs
		$('#nwslttrErrorCntr').addClass('hidden');
		loaderAnim(true);
		
		// stop form submit
		evt.preventDefault();
		
		var url = baseURL + 'index.php/newsletter/submit';
		
		$.post( url, $(this).serializeArray(), function(data) {	
			
			loaderAnim(false);
			
			if ( data.indexOf('isSuccess') > -1 && ! data.indexOf('isError') > -1 )
			{
				getNwsltrSuccess();
			}
			else
			{
				$('#nwslttrErrorCntr p').remove();
				$('#nwslttrErrorCntr').removeClass('hidden');
				$(data).appendTo('#nwslttrErrorCntr');
			}
			
		});	
		
	});
});

// action for fb fake msg
$(function(){
	$('#singleProductWrp').delegate('#sNetWrknWrp', 'hover', function(){
		$('#fakeInfoFb').fadeOut();
	});
});

// action for setting searchbox filters
$(function(){
	
	var filterInputCase = function(fName){	
			if ( ! $('#searchForm').find('#is_' + fName).length > 0 )
			{
				var curFilter = fName;
				var curInput = '<input id="is_' + fName + '" type="hidden" name="filters[]" value="' + curFilter + '">';
				$(curInput).appendTo('#searchForm');
			}
			else
			{
				$('#is_' + fName).remove();				
			}
	}
	
	var isFilterType = function(el, fName){
		return $(el).parent('li').attr('class').indexOf(fName) > -1 ? $(el).parent('li').attr('class').indexOf(fName) : false;
	}
	
	$('#searchBoxFilters').delegate('ul._filters li a', 'click', function(){
		
		if ( isFilterType(this, 'promo') )
		{
			var fName = 'promo';
			filterInputCase(fName);
		}
		else if (  isFilterType(this, 'topConfo') )
		{
			var fName = 'topConfo';
			filterInputCase(fName);		
		}
		else if ( isFilterType(this, 'firstPrice')  )
		{
			var fName = 'firstPrice';
			filterInputCase(fName);	
		}
		else if ( isFilterType(this, 'exclusiveWeb')  )
		{
			var fName = 'exclusiveWeb';
			filterInputCase(fName);	
		}
		
	});
});

// action for setting searchbox category
$(function(){
	
	$('._cats').delegate('.ddList .listing li', 'click', function(){
		var curCat = $(this).find('span.value').text();
		$('#formSearchCat').val(curCat);		
	});
	
});

// action for setting searchbox price range
$(function(){
	$('#searchBoxFilters').delegate('ul#prices li ul.listing li','click', function(){
		var curPriceRng = $(this).find('span.value').text();
		
		$('#formSearchPriceRng').val(curPriceRng);
	});
});

// action for user login
var keepTopLoginBoxOpen = function(state){
	if ( state )
	{
		$('#loginWrp .ajaxLoader').removeClass('hidden');
		$('._login').addClass('topLoginBack');
		$('._login #loginWrp').addClass('loginWrpVisible');
	}
	else
	{
		$('#loginWrp .ajaxLoader').addClass('hidden');
		$('._login').removeClass('topLoginBack');
		$('._login #loginWrp').removeClass('loginWrpVisible');
	}
};

var showLoggedUserMenu = function(state){

	if ( state )
	{	
		setTimeout(function(){
			$('#menuLoggedIn').removeClass('hidden');
			$('#topLogin').addClass('hidden');
			$('#menuLoggedIn ul li a.logout').removeClass('asyncCall');
			$('#menuTopHeader ._login > a.lgnTitle').text('Cliente');
		},1000);
	}
	else
	{
		setTimeout(function(){
			$('#menuLoggedIn').addClass('hidden');
			$('#topLogin').removeClass('hidden');
			$('#menuTopHeader ._login > a.lgnTitle').text('Login');
		},1000);
	}
};

$(function(){
	
	$('#loginWrp').delegate('.submitUserLogin','click',function(e){
		
		keepTopLoginBoxOpen(1);
	
		e.preventDefault();
		var curForm = $(e.currentTarget).parents('form');
		var curUrl = baseURL + 'index.php/client/signin';
		var curData = curForm.serializeArray();		

		$.post( curUrl, curData, function(data) {		
			
			getContent(data);
				
			if (  $(data).find('.isError').length > 0  )
			{
				keepTopLoginBoxOpen(0);
				showLoggedUserMenu(0);			
			}
			else
			{
				keepTopLoginBoxOpen(0);
				showLoggedUserMenu(1);			
			}
			
		});

	});
	
});

// action to show modify pw
var showModifyPw = function(state){
	if ( state )
	{
		$('#userAuthModifyPw').removeClass('hidden');
		$('#changePw').text('Cancelar modificação de senha');
	}
	else
	{
		$('#userAuthModifyPw').addClass('hidden');
		$('#changePw').text('Clique aqui para modificar senha');
	}
};

$(function(){
	//unobstructive javascript approach
	//if there's JS will add / remove hidden accordingly
	$('#changePw').removeClass('hidden');
	$('#userAuthModifyPw').addClass('hidden');

	$('#formUserProfile').delegate('#changePw','click',function(){
		var state = $('#userAuthModifyPw').attr('class').indexOf('hidden') > -1 ? true : false;
		showModifyPw(state);
	});
});

// action remove from cart
var getCheckOutPage = function(){
		$.post( baseURL+'index.php/orders/checkout/1', function(data){
			$("#content").html( $(data).find("#content").html() );
		});
};
var removeRawIfCartCheckOut = function(el){

	if ( $(el.currentTarget).parents('.eachProdRawLine').length == 0 )
	{
		getCheckOutPage();
	}
	else
	{
		$(el.currentTarget).parents('.eachProdRawLine').remove();	
	}
}
$(function(){
	$('body').delegate('a.remove_from_cart','click',function(e){

		e.preventDefault();
		loaderAnim(true);

		var curUrl = $(e.currentTarget).attr('href') + '/ajax';

		$.post( curUrl, function(data){
				replaceCartTable(data);
				getCartTotal();
				removeRawIfCartCheckOut(e);				
		});

	});
});

// action modify delivery
var showDeliveryAddrss = function(){
	$('#deliveryAddress').removeClass('hidden');
	$('#rootBackDarkBox').removeClass('hidden');
}
$(function(){
	$('body').delegate('a.modifyDlvrAddrss','click', function(e){
		e.preventDefault();
		showDeliveryAddrss();
	});
});

var closeDeliveryAddrssUpdate = function(e){
		e.preventDefault();
		$(e.currentTarget).parents('#deliveryAddress').addClass('hidden');
		$('#rootBackDarkBox').addClass('hidden');
};
// action close modify delivery
$('#deliveryAddress ._xClose').live({
	click : function(e){
		closeDeliveryAddrssUpdate(e);
	}
});

// action save order address
$('#formAddressUpdate').live({
    submit : function(e){
        e.preventDefault();
        var curUrl = $(e.currentTarget).attr('action');

		$.post( curUrl, $(this).serializeArray(), function(data) {	
			if ( data.indexOf("hasErrors") > 0 )
			{
				$('#errorsUpdtOrdAddrWrp ._listErrors').html( data );
				$('#errorsUpdtOrdAddrWrp').removeClass('hidden');
			}
			else if ( data.indexOf("hasSuccess") > 0 )
			{
				closeDeliveryAddrssUpdate(e);
			}
			else
			{
				alert('Unexpected error!');
			}
		});

    }
});
//action for NewUserRegistration
/*
$('#formNewUser form').live({
	submit : function(e){
		e.preventDefault();
		
		loaderAnim(true);
	
		var curEl =	$(e.currentTarget);
		var curUrl = curEl.attr('action');
		
		$.post( curUrl, curEl.serializeArray(), function(data) {
			if ( $(data).find(".hasErrors").length > 0 )
			{
				getContent(data);
				loaderAnim(false);
			}
			else
			{
				getContent(data);
				loaderAnim(false);
			};
		});
	}
});
*/


// action for order finish
/*
$('form#checkoutFinishStep').live({
	submit : function(e){
		e.preventDefault();
		var curUrl = $(e.currentTarget).attr('action');
		
		$.post( curUrl, $(this).serializeArray(), function(data) {	
			if ( $(data).find(".hasErrors").length > 0 )
			{
				$('#errorsUpdtOrdAddrWrp ._listErrors').html( data );
				$('#errorsUpdtOrdAddrWrp').removeClass('hidden');
			}
			else if ( $(data).find(".hasSuccess").length > 0 )
			{
				getContent(data);
			}
			else
			{
				alert('Unexpected error!');
			}
		});
		
	}
});
*/

// disable autocomplete for searchengine inputbox
$(function(){
	$('#searchInpTxt').attr('autocomplete','off');
});
var scrollWindowUp = function(){
	$('html, body').animate({scrollTop:0}, 'slow');
};
$(function(){
	$('.sysMsgBtnGoBackHistory a').live({
		click: function()
		{
			history.go(-1);
		}
	});
});
var ocasionalScripts = function(){

	$(function(){
		setTimeout(function(){
			$(".formToValidate").validate();
		},2000);
	});
	
};
