//Currency selection vars
var options = new Array();
var selectedItem;	
var curSelection;	
var count=0;
var oTemp = {}; 
var aTempObjs = new Array();
var currencyId;

//Customer comment vars
var timer = 6500;
var scroller = false;
var activeClass = 'active';
var fader = 1500;
var item = '.comment.active';
var commentSkipTimer = 500;

var growler = false;
var growlDuration = 5000;

$(document).ready(function(){
	
	/* ##################################### Currency selection */
	
	initSelectionList();
	
	
	//Append an image to the list to act as a control for the user to utilise
	// only if basket is not created 

	if ($('#hid_currency_enable').val()) {
		$('#currency-select div.jsOptions').append('<img src="/_assets/img/system/down-arrow.jpg" width="13" height="13" />');
	}	


	function initSelectionList(){
		//Get each of the values from the HTML select list so we can create a prettier list. Firstly find the selected item
		$('#currency-select select option').each(function(index){
				
			if($('#currency-select select option[selected=selected]').text() == $(this).text()) {				
				
				currencyId = $(this).attr('value');				
				curSelection = {
						'key' : $(this).attr('value')
						,'value' : $(this).text()
						,'selected' : true
				};
				options.push(curSelection);
			}
			else{				
				if($(this).text() != 'undefined')
				{
					oTemp = {
						'key' : $(this).attr('value')
						,'value' : $(this).text()
						,'selected' : false
					};
					aTempObjs.push(oTemp);					
				}								
			}
			count++;
		});		
				
		
		//merge the arrays together so we can iterate through all options, with the selected item at the top
		options = $.merge(options, aTempObjs);

		
		//Append a new element to the selection list based on how many items are in the object
		$.each(options, function(index, value){
			$('#currency-select div.jsOptions').append('<span id="'+options[index].key+'">'+options[index].value+'</span>');
			
			if(options[index].selected)
				selectedItem = options[index].key;
		});
	}	
	
	
	//Calculate the various values needed for the menu to work
	var containerOriginalHeight = $('#currency-select div.jsOptions').css('height'); 
	var itemHeight = $('#currency-select div.jsOptions span').css('height');
	var currencies = $(options).length;	
	var containerHeight = parseInt(itemHeight)*currencies;


	//Actions to carry out when the user clicks the arrow (open or close the list)
	$('#currency-select div.jsOptions img').click(function(e){
		e.preventDefault();
		if($(this).parent().css('height') == containerOriginalHeight) {
			$('#currency-select div.jsOptions').css('height', containerHeight);
		}	
		else{
			$('#currency-select div.jsOptions').css('height', containerOriginalHeight);
		}
		
		//Set a timer so that if the selection list is still open after a 5 seconds it is closed automatically
		setTimeout(function(){
			$('#currency-select div.jsOptions').css('height', containerOriginalHeight);
		}, 5000);
	});
	
	
	//Actions to carry out if the user selects an option from the list
	$('#currency-select div.jsOptions span').click(function(e){
		e.preventDefault();		
		
		//If the item is the currently selected one then just close the list
		if($(this).attr('id') == selectedItem)
			$('#currency-select div.jsOptions').css('height', containerOriginalHeight);
		//Otherwise fire off an ajax event to store the new selection in the session. Then reload the current page
		else{
						
			var data = {
				currencyId : $(this).attr('id')
				,fromJs : true
			};
			
			$.ajax({
				url: "/home/changeCurrency"
				,type : 'post'
				,async : true
				,data : data
				,dataType : 'json'
				,success: function(response){
					
					if(response.success)
						window.location = document.URL;
			  }
			});
		}			
	});
	
	
	/* ##################################### Shopping basket hover */
	
	
	$('#top-right-header li#basket').hover(function(){
		$(this).addClass('active');
		$('#top-right-header li#basket ul').css('display', 'block');
	}, function(){
		$(this).removeClass('active');
		$(this).removeClass('newItemAdded');
		$('#top-right-header li#basket ul').css('display', 'none');
	});
	
	
	/* ##################################### Shopping basket new item added */
		
	if($('#top-right-header li#basket').hasClass('newItemAdded')) {		
		setTimeout(function(){
			$('#top-right-header li#basket').removeClass('newItemAdded');
		},5000);		
		newGrowlMessage('A new product has been added to your basket');		
		_gaq.push(['_trackEvent', 'Basket', 'Add']);
	}
	
	/* ##################################### Customer Comments Module */
	
	
	var btnPrevious = "<span id='previous' title='Previous comment'><a href='#'>Previous</a></span>";
	var btnNext 	= "<span id='next' title='Next comment'><a href='#'>Next</a></span>";	
	var cCounter	= "<span id='cCount'><span id='current'>1</span> of <span id='total'>-</span></span>";	
	var cTotal 		= ($('#comments .comment').length);
		
	//If there are enough comments then out in some navigation controls
	if($('#comments .comment').length > 1){
		$('#customer-comments-module').append(btnPrevious);
		$('#customer-comments-module').append(btnNext);
		$('#customer-comments-module').append(cCounter);
		scroller = setTimeout("navigate()", timer);
	}
	else {
		$('#customer-comments-module #comments').css('height', 'auto');
	}
	
	//Display the number of comments to the user
	$('#total').html(cTotal);
	
	$('#customer-comments-module a').live('click', function(e)
	{		
		e.preventDefault();
		clearTimeout(scroller);
		
		if ($(this).parent().attr('id') == 'next'){ 
			/* Next button click. If we aren't at the end then go to the next item in the list */
			if($(item).index() < $('#comments .comment').length-1){				
				var thisItem = $(item); 				
				$(thisItem).children().animate({opacity:0}, commentSkipTimer, function(){					
					$(thisItem).next().addClass(activeClass);
					$(thisItem).removeClass(activeClass);
					$('.comment.active').children().animate({opacity:1}, commentSkipTimer);
					$('#cCount #current').html($('.comment.active').index()+1);
				});			
			}
			/* Next button click. If we are at the end then go back to the beginning of the list */
			else {
				var thisItem = $(item);
				$(thisItem).children().animate({opacity:0}, commentSkipTimer, function(){					
					var nextItem = $(thisItem).parent().find('div.comment:eq(0)'); 
					$(thisItem).removeClass(activeClass);
					nextItem.addClass(activeClass);
					nextItem.children().animate({opacity:1}, commentSkipTimer);
					$('#cCount #current').html('1');
				});
			}
		}
		else if ($(this).parent().attr('id') == 'previous') {
			/* Previous button click. If we aren't at the beginning of the list then go to the last item displayed */
			if($(item).index() > 0){
				var thisItem = $(item);
				$(thisItem).children().animate({opacity:0}, commentSkipTimer, function(){					
					$(thisItem).removeClass(activeClass);
					$(thisItem).prev().addClass(activeClass);
					$(thisItem).prev().children().animate({opacity:1}, commentSkipTimer);
					$('#cCount #current').html($(thisItem).index());
					console.log($(thisItem).index())
				});
			}
			/* Previous button click. If we aren't at the beginning of the list then go to the last item in the list */
			else {
				var lastItemIndex = $('#comments .comment').length-1;
				var thisItem = $(item);
				var nextItem = $(thisItem).parent().find('div.comment:eq('+lastItemIndex+')');
				
				$(thisItem).children().animate({opacity:0}, commentSkipTimer, function(){					 
					$(thisItem).removeClass(activeClass);
					$(nextItem).addClass(activeClass);
					$(nextItem).children().animate({opacity:1}, commentSkipTimer);
					$('#cCount #current').html(cTotal);
				});
			}
		}
	});
	
	var thisClickedLink;
	var element;
	var duration = 500;
	
	$('#customer-comments-module p#post-comment-link  a').click(function(e){
		e.preventDefault();
		
		$('#customer-comments-module #previous').hide();
		$('#customer-comments-module #next').hide();
		$('#customer-comments-module .comment').hide();
		$('#customer-comments-module #creator').show();
		thisClickedLink = $(this);		
		thisClickedLink.hide();		
		thisClickedLink.parent().append('<a id="cancel-comment" href="#">Cancel</a>');		
		
		element = $('#customer-comments-module #creator'); 
		element.animate({
			height : '185px'
			,opacity : 1
		},duration);
	});
	
	$('#customer-comments-module a#cancel-comment').live('click', function(e){
		e.preventDefault();
		element.animate({
			height : 0
			,opacity : 0
		},duration, function(){
			$(element).find('textarea').val('');
		});				
		$(this).hide();
		$('#comments .error').html('');		
		thisClickedLink.show();
		$('#customer-comments-module .comment').show();
		$('#customer-comments-module #previous').show();
		$('#customer-comments-module #next').show();
	});
	
	$('#customer-comments-module #sbm_comment_form').click(function(e){
		e.preventDefault();
		var formData = $('#frm-comment-form').serialize();
		
		formData += '&js=true';
		formData += '&sbm_comment_form=true';
		
		$.ajax({
			type : 'POST'
			,data : formData 
			,url : '/comments/createComment'
			,dataType: "json"
			,success : function(response){
				
				if(response.success) {					
					$('#customer-comments-module #creator').hide();
					$('#customer-comments-module a#cancel-comment').remove();					
					$('#customer-comments-module #comments').append('<a id="post-done" href="done">Thanks, I\'m done.</a>');
				}									
				$('#comments .error').append(response.commentMessage);
			}
		});
	});
	
	$('#customer-comments-module a#post-done').live('click', function(e){
		e.preventDefault();
		$('#comments .error').html('');
		$(element).find('textarea').val('');
		$('#customer-comments-module #previous').show();
		$('#customer-comments-module #next').show();
		$('#customer-comments-module .comment').show();
		thisClickedLink.show();	
		$(this).remove();
	});
});

/* Scroller for the customer comments module. Initiated on page load and auto scrolls this listed elements */
function navigate()
{	 	
	if (scroller != false)
		clearTimeout(scroller); 	
	$('#customer-comments-module #next a').trigger('click');	 
	scroller = setTimeout("navigate()", timer);
}

function newGrowlMessage(message)
{
	var growlRadius = '4px';		
	growler = true;
	
	if($('#growler').length > 0)
		$('body').remove();
	
	$('body').append('<div id="growler"></div>');	
	$('#growler').append('<div id="growl-msg"></div>');
	$('#growl-msg').append('<span id="growl-overlay"></span>');
	$('#growl-msg').append('<p>'+message+'</p>');
	
	$('#growler').css({
		position : 'fixed'
		,bottom : '15px'
		,right : '15px'
		,'z-index' : 10		
		,'border-radius' : growlRadius 
		,'-moz-border-radius' : growlRadius
		,'-webkit-border-radius' : growlRadius
		,opacity : 0
	});
	
	$('#growl-msg').css({
		width : '250px'
		,position : 'relative'		
	});
	
	$('#growl-msg span').css({
		width : $('#growl-msg').css('width')-'10px'
		,height : $('#growl-msg').css('height')
		,bottom : 0
		,left : 0
		,background : '#000000'
		,display : 'block'
		,opacity : '0.8'
		,padding : '10px'
		,'z-index' : 5
		,'border-radius' : growlRadius
		,'-moz-border-radius' : growlRadius
		,'-webkit-border-radius' : growlRadius
	});
	
	$('#growl-msg p').css({
		position : 'absolute'
		,top : '5px'
		,left : 0	
		,'z-index' : 20
		,color : '#ffffff'
		,width : $('#growl-msg').css('width')-30
		,'text-align' : 'center'
	});
	
	
	$('#growler').animate({
		opacity : 1
	}, 900, function(){
		setTimeout(function(){
			$('#growler').animate({
				opacity : 0
			}, 900, function(){
				growler = false;
			});
		}, growlDuration);
	});
}


