//make sure errors don't happen in other browsers
if (!window.console){
	window.console = {	
		log:function(){},
		error:function(){},
		warn:function(){},
		info:function(){},
		assert:function(){},
		time:function(){},
		timeEnd:function(){},
		dir:function(){},
		debug:function(){},
		group:function(){},
		groupEnd:function(){},
		count:function(){}
	};
}


$(function() {
	
	//make character list managable
	$('.characterlistitems').hide();
		
	$('.characterlisttrigger').click(function(){	
		if($(this).attr('class') === 'characterlisttrigger open'){
			$('#'+$(this).attr('id')+' span').html('[+]');
			$(this).removeClass('open');
			$('.'+$(this).attr('id')).fadeOut(500);
		}else{
			$('#'+$(this).attr('id')+' span').html('[-]');
			$(this).addClass('open');
			$('.'+$(this).attr('id')).fadeIn(500);
		}
	});

	//promotion Popups
	$('.promoDescLink').mouseover(function(){
		$(this).nextAll('.promoDesc:first').show().animate({top: '+=10px',opacity: 1},400);
	});
	
		$('.promoDescLink').mouseout(function(){
		
		$(this).nextAll('.promoDesc:first').animate({top: '-=10px',opacity: 0},400, function(){$(this).hide();}  );
	});

	function testing(){
		$("#checkout_wrapper-paymentinfo .shoppingcart_items").load("/shop/cart/thanks.php");
	}

	// Remove the search label and use its text to populate the field
	var searchLabel = $('#search label').remove().text();
			
	$('#q').addClass('placeholder').val(searchLabel).focus(function() { 
		if (this.value == searchLabel) { 
			$(this).removeClass('placeholder').val(''); 
		}; 
	}).blur(function() { 
		if (this.value == '') { 
			$(this).addClass('placeholder').val(searchLabel); 
		}; 
	});
	
	// One glitch caused by the enhancement remains; if the form is submitted without 
	// 	user input, the field could still contain the placeholder text. To avoid this, we return false 
	// 	when the form is submitted:
	$('#search').submit(function() { 
		if ($('#q').val() == searchLabel) return false;
	});
	
	var totalProducts = $('#showProducts').val();
	
	var totalCategories = $('#showCategories').val();
	
	var currentTotal =  parseInt(totalProducts) + parseInt(totalCategories);
	
	// Toggle category search results
	$('#showCategories').click(function() {
		$('#searchResultCategoriesBlock').toggle();
	}).click();
	
	// Toggle product search results
	$('#showProducts').click(function() {
		$('#searchResultProducts').toggle();
		$('#productPagination').toggle();
	}).click();
	
	
	// Close userSuccessMessage
	$('#viewCartTop').click(function(){
		window.location.href = '/shop/cart/';
		return false;
	});
	
	// Close userSuccessMessage
	$('#closeMessageTop').click(function(){
		hideUserSuccessMessage();
		return false;
	});
	
	
	// Product detail add to cart
	$('form.addProductPage').submit(function() 
	{	
	
		var itemQtyValue = 0;
		
		$('input[name="qty[]"]',this).each(function(i){
			
			itemQtyValue += ($(this).val() - 0);
			
		});
		
		//var attributeList = '';
		var params = $(this).serialize();
	
		// Show loading indicator
		
		blockMessage('.product-add_to_cart');
		
	//	$('.addToCart').addClass('spinmeround');
		
		//alert('called ajax');
		
		// Send the post
		$.ajax({
			
			type: 'POST',
			url: '/shop/cart/add.ajax',
			cache: false,
			data: params,
			success: function(data) {
			
				console.log(data);
			

				// Create new totals
				var newTotals = data.split(',');
				
				$('#cart_amount').html(newTotals[1]);
				$('#cart_quantity').html(newTotals[0]);
							
				setTimeout("unBlockMessage('"+itemQtyValue+"','normal','"+newTotals[0]+"','"+formatCurrency(newTotals[1])+"','.product-add_to_cart')", 1500);
				
				if (newTotals[0] == '1') {
					$('.cart_recap span').text(newTotals[0]+' Item');
				} else {
					$('.cart_recap span').text(newTotals[0]+' Items');
				}
				
				$(".cart_recap_items").load("/assets/common.php", { 'action': "cart_refresh" } );
				
				
			},
			error: function() {
				// Create new totals
				alert ('An AJAX error occoured.');
			}
		});
		return false;
	});

	// Product category add to cart
	$('form.addProduct').submit(function() 
	{
		
		
		
		var itemPid = $(this).find("input[name='pid']").val();
		var itemPrice = $(this).find("input[name='price']").val();
		var itemQty = $(this).find("input[name='qty']");
		var addButton = $(this).find('button');
		var form = '"#pick'+itemPid+'"';
		
		
		var params = $(this).serialize();
		
			
		if (!itemQty.val()) {
			var itemQtyValue = '1';
		} else {
			var itemQtyValue = itemQty.val();
		}
		
		//alert(params);
		
		if (itemQtyValue) 
		{
			// Fade add button out
			//addButton.hide();
			//addButton.fadeOut('normal', function() {
				// Show loading indicator
				//blockMessage(form);
				//setTimeout("blockMessage("+form+")", 200);
				// Send the post
					
				blockMessage('#productlistingboxid'+itemPid);
				
				$.ajax({
					type: 'POST',
					url: '/shop/cart/add.ajax.php',
					cache: false,
					data: params,
					success: function(data) {
					
						// Create new totals
						var newTotals = data.split(',');
						// Remove loading indicator
						
						$('#cart_amount').html(newTotals[1]);
						$('#cart_quantity').html(newTotals[0]);
						
						setTimeout("unBlockMessage('"+itemQtyValue+"','small','"+newTotals[0]+"','"+formatCurrency(newTotals[1])+"','#productlistingboxid"+itemPid+"')", 200);
					
					
					
		/*
				
					if (newTotals[0] == '1') {
						$('.cart_recap span').text(newTotals[0]+' Item');
					} else {
						$('.cart_recap span').text(newTotals[0]+' Items');
					}
					
*/
					
					
					
					
					//met only
					//$('#pick'+itemPid).children(".add_to_cart").trigger('click');
					//$(".cart_recap_items").load("/assets/common.php", { 'action': "cart_refresh" } );
						
					}
				});
		}	
		return false;
	});

	        $('#viewCart').livequery('click', function(event) { 
	            // update the block message 
				$.blockUI({ 
					message: "<h3>Redirecting to your cart...</h3>", 
					css: { border: 'none', 
						   padding: '15px', 
					       backgroundColor: '#816985', 
					       '-webkit-border-radius': '5px', 
					       '-moz-border-radius': '5px', 
					       opacity: '0.9',
					 	   fontSize: '14px',
					       color: '#fff' 
						}, 
					overlayCSS:  {  
				        backgroundColor: '#d4b9e2',  
				        opacity:        '0.5'  
				    }
				 });
				location.href='/shop/cart/'; 
	        }); 

	        $('#continueShopping').click(function() { 
	            $.unblockUI(); 
	            return false; 
	        });
	       
	        
	    //$("#navlist").accordion();


    
    $('.menu_'+$('#current_page').val()).css('color','yellow');
    
    page_open_ul('#menu_'+$('#open_menu').val());
    
	        
});



function open_ul (ul){
	//alert(ul);
	$(ul).animate({height: 'toggle', opacity: 'toggle'});
	$(ul).parents('li a').toggleClass('opened');
	$(ul).siblings('ul').slideUp('fast').toggleClass('opened');
}


function page_open_ul (ul){
	//alert(ul);
	$(ul).show();
	$(ul).parents('li a').toggleClass('opened');
//	$(ul).siblings('ul').slideUp('fast').toggleClass('opened');
}












// Function to format currency
function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
}

function blockMessage(element){
	$(element).block({  
		message: '<img src="/assets/layout/ajax-loader.gif" alt="" style="vertical-align: top;" />',
		css: { 
				border					: 'none'		,
		       	padding					: '0px 0px'		, 
		       	backgroundColor			: '#cbdc2e'		, 
		       	'-webkit-border-radius'	: '5px'			, 
		       	'-moz-border-radius'	: '5px'			, 
		       	opacity					: '0.75'		,
		 	   	fontSize				: '11px'		,
		       	color					: '#fff'
			}, 
		overlayCSS:  {  
	        	backgroundColor		: '#cbdc2e'		,  
	        	opacity				: '0.7'  
	    },
		centerX: true, // <-- only effects element blocking (page block controlled via css above) 
	    centerY: true
	});
}



function blockCart(element){
	$(element).block({  
		message: '<img src="/assets/layout/ajax-loader.gif" width="31" height="31" border="0" alt="" style="margin: 0 0 0 -5px; padding: 0;" />',
		css: { 
				border					: 'none'		,
		       	padding					: '8px 15px'	, 
		       	backgroundColor			: '#cbdc2e'		, 
		       	'-webkit-border-radius'	: '5px'			, 
		       	'-moz-border-radius'	: '5px'			, 
		       	opacity					: '0.75'		,
		 	   	fontSize				: '11px'		,
		       	color					: '#fff'		
			}, 
		overlayCSS:  {  
	        	backgroundColor		: 	'#cbdc2e'	,  
	        	opacity				:   '0.4'  
	    },
		centerX: true, // <-- only effects element blocking (page block controlled via css above) 
	    centerY: true
	});
}


function unBlockMessage(value, type, totalItems, subTotal, unblockElement){
	$(unblockElement).unblock();

	// Update the new totals	
	$('span#cartTotalItems em').text(totalItems);
	$('span#cartSubTotal em').text(subTotal);
	
	if (totalItems == '1'){
		$('#top-cart strong span.item').text('item');
	} else {
		$('#top-cart strong span.item').text('items');
	}
	
	if (value == '1') {
		var message = '<strong>1</strong> item was added to your cart!';
	} else {
		var message = '<strong>'+ value +'</strong> item(s) were added to your cart!';
	}
	
	// Display success message
	// blockSuccess(message);
	userSuccessMessage(message);
	
	// Remove success message
	setTimeout("hideUserSuccessMessage()", 5000);	
	
	// Show add buttons
	$('form.addProduct > button').show();
		
}


function blockSuccess(string){
	jQuery.blockUI({
		message: string + '<br /><button id="viewCart">View Cart</button>',
		css: { border: 'none', 
		       padding: '15px', 
		       backgroundColor: '#816985', 
		       '-webkit-border-radius': '5px', 
		       '-moz-border-radius': '5px', 
		       opacity: '0.9',
		 	   fontSize: '20px',
		       color: '#f4efea'
			}, 
		overlayCSS:  {  
	        backgroundColor: '#d4b9e2',  
	        opacity:        '0.5'  
	    },
		centerX: true, // <-- only effects element blocking (page block controlled via css above) 
	    centerY: true
    }); 

    setTimeout(jQuery.unblockUI, 2000);	
		
}


function userSuccessMessage(string)
{
	$('#successMessageTop span').html(string);
	$('#successMessageTop').fadeIn();
    //setTimeout(jQuery.unblockUI, 2000);			
}

function hideUserSuccessMessage()
{
	$('#successMessageTop').fadeOut();			
}

function removeSuccess(type)
{
	switch(type)
	{
		case 'normal':
			$('div.successMessage').fadeOut();
			break;    
		case 'small':
	  		$('div.successMessageSmall').fadeOut(function() {
				$('form.addProduct button').fadeIn();
			});
	  		break;
	}
}



