$(document).ready(function(){ 
    
// put your custom jScript here - will execute on completion of DOM load	
	
	// function to populate a form-field with a default text as description
	function populateElement(selector, defvalue) {
	    $(selector).each(function() {
	        if($.trim(this.value) == "") {
	            this.value = defvalue;
	        }
	    });
	
	    $(selector).focus(function() {
	        if(this.value == defvalue) {
	            this.value = "";
	        }
	    });
	
	    $(selector).blur(function() {
	        if($.trim(this.value) == "") {
	            this.value = defvalue;
	        }
	    });
	 }
	
	// tell which element to populate with what text
	populateElement('#s', 'Enter search text');
	populateElement('#w', 'Enter search text');
	populateElement('#mailing-name', 'Name*');
	populateElement('#mailing-email', 'Email*');
	populateElement('#mailing-details', 'Please also let us know if you have any areas of special interest.');
	
	
	// function to change input bg color; on hover, and if text input is different than default
	function changeBackground(item, initialValue, startColor, onChangeColor, endColor){
			
			// 4 all items 
		    $(item).each(function() {
	        
	        if($.trim(this.value) == initialValue) {
	            
	            $(this).css({
    			'background-color' : startColor, 
    			'color' : 'white'
    			});
    			
	        }else if($.trim(this.value) == ''){
	        	
	        	this.value = initialValue;
	        	
	        	$(this).css({
    			'background-color' : onChangeColor, 
    			'color' : 'black'
    			});
	        
	        }else{
	        	
	        	$(this).css({
    			'background-color' : endColor, 
    			'color' : 'white'
    			});
	        }
	    });
	
		// on focus
	    $(item).focus(function() {
	   
	        if($.trim(this.value) == initialValue) {
	            
	            this.value = "";
	            
	            $(this).css({
    			'background-color' : startColor, 
    			'color' : 'white'
    			});
    			
	        }else if($.trim(this.value) == ''){
	        	
	        	this.value = "";
	        	
	        	$(this).css({
    			'background-color' : onChangeColor, 
    			'color' : 'black'
    			});
	        
	        }else{
	        	
	        	this.value = "";
	        	
	        	$(this).css({
    			'background-color' : endColor, 
    			'color' : 'white'
    			});
	        }
	   
	    });
		
		// on blur
	    $(item).blur(function() {
	       	
	        if($.trim(this.value) == initialValue) {
	            
	            $(this).css({
    			'background-color' : startColor, 
    			'color' : 'white'
    			});
    			
	        }else if($.trim(this.value) == ''){
	        	
	        	this.value = initialValue;
	        	
	        	$(this).css({
    			'background-color' : onChangeColor, 
    			'color' : 'black'
    			});
	        
	        }else{
	        	
	        	$(this).css({
    			'background-color' : endColor, 
    			'color' : 'white'
    			});
	        }
	    });
    	
    } 
    
    // change bg of the input box --- ID, text, startColor, onChangeColor, endColor 	 	
  	changeBackground('#mailing-name','Name*', '#2a010e','#E1B0B0','#990033');
  	changeBackground('#mailing-email', 'Email*','#2a010e','#E1B0B0','#990033');
	changeBackground('#mailing-details', 'Please also let us know if you have any areas of special interest.','#2a010e','#E1B0B0','#990033');
	
	
	// scroll back to top - smoooooooth
	$('a.backtotop').click(function(){
		 $('body').scrollTo( { top:0 , left:0}, 400, {easing:'easeInOutCubic'});
         return false;
	});
	
	// mailing list 
	$('#mailing-list-search').live('submit',function() {
		var fname = $('#mailing-name').val();
	    var femail = $('#mailing-email').val();
	    var fdetails = $('#mailing-details').val();
	    $.post(
	    	'/contact/mailing-ajax',
	    	{name: fname, email: femail, details: fdetails},
	    	function(data){
	    		$('#mailing-ajax').html(data);
	    });
	    return false;
	});


	// Appellations Coolapsible panel
	jQuery("#appellation-wrapper").hide();
	//toggle the component with id #appellation-wrapper
	jQuery("#expander").click(function() {
	    jQuery("#appellation-wrapper").slideToggle(500);
	    jQuery("span.closed").toggleClass("open");
	    
	});

	
	//toggle the critics tables
    $(".button-toggle").click(function() {
    	$(this).next(".all-critics").slideToggle(600);
    	if ($(this).html() == 'Hide the tasting notes') {
    		$(this).html('Show the tasting notes');
    		$(this).addClass("expand").removeClass("close").attr('title', 'Show the tasting notes');
    	} else {
    		$(this).html('Hide the tasting notes');
    		$(this).addClass("close").removeClass("expand").attr('title', 'Hide the tasting notes');
    	}
    	return false;
    });
    
      
    // Tooltips
    $('a.commerce[title], span.commerce[title]').tinyTips('black', 'title');
    
    
    
    // Delivery options
    // From the start hide all the delivery elements (only show the parent options)
     $('.delivery-elements').hide();
    
    // If one is checked (when returning on the page either because the form is not valid or to edit the form)
    $(".delivery-form input[type='radio']:checked").parent().next(".delivery-elements").show();
    
   // Clicking on one of the parent delivery option:
    $('.delivery_option').click(function() {
    	$('.delivery-elements').hide();
    	$(this).parent().next(".delivery-elements").fadeIn(600);
    });
    
    
    
    // This function is used to update the quantities in the different baskets
    $(".quantity-select").change(function() {
    	
    	var selectElement = $(this).attr('id');
    	var selectElements = selectElement.split("-");
    	var btlCs = selectElements[0];
    	var orderLineId = selectElements[1];
    	var listTypeId = selectElements[2];
    	var basketId = selectElements[3];
    	
    	if (btlCs == 'cases') {
    		var casesQuantity = $(this).attr('value');
    		var bottleId = "#bottles-"+orderLineId+"-"+listTypeId+"-"+basketId; 
    		if ($(bottleId)) {
    			var bottlesQuantity = $(bottleId + " :selected").attr('value');
    		} else {
    			var bottlesQuantity = 0;
    		}
    	} else {
    		var bottlesQuantity = $(this).attr('value');
    		var caseId = "#cases-"+orderLineId+"-"+listTypeId+"-"+basketId; 

    		if ($(caseId)) {
    			var casesQuantity = $(caseId +" :selected").attr('value');
    		} else {
    			var casesQuantity = 0;
    		}
    	}
    	 
    	 $.ajax({ 
   		  type: 'POST', 
   		  url: "/lists/update-quantity", 
   		  data: { 
   			  	listTypeId : listTypeId,
   			  	basketId : basketId,
 				orderLineId:orderLineId,
 				casesQuantity:casesQuantity,
 				bottlesQuantity:bottlesQuantity,
 				type:btlCs
 				
   			},
   			success: function(data,textStatus,jqXHR){
   				var results = jQuery.parseJSON(data);
   				
   				$("#units-"+results.orderLineId).html(results.units);
   				if (results.listTypeId == 1) {
	   				$("#price-"+results.orderLineId).html(currencyFormat(results.price));
	   				$("#total-price_"+results.listTypeId).html(currencyFormat(results.totalPrice));
   				} else if (results.listTypeId == 3) {
   					$("#min_estimated_price-"+results.orderLineId).html(currencyFormat(results.minEstimatedPrice));
   					$("#max_estimated_price-"+results.orderLineId).html(currencyFormat(results.maxEstimatedPrice));
   					$("#min_total_estimated-"+results.listTypeId).html(currencyFormat(results.minTotalEstimated));
   					$("#max_total_estimated-"+results.listTypeId).html(currencyFormat(results.maxTotalEstimated));
   				}
   				

   			},
   			error: function(xhr, textStatus) {
   				/*if (xhr.status == '404') {
   					alert('Sorry, page not found');
   				}
   				// Do we have a JSON response? Ignore any errors on the JSON parsing
   				try {
   					var response = jQuery.parseJSON(xhr.responseText);
   					alert('PHP Error: ' + response.message);
   				} catch (e) {
   					// Return standard error alert message
   					if (xhr.status == '500') {
   						alert("Sorry, there's been a server error");
   					} else {
   						alert("Sorry, there's been an error: " + textStatus);
   					}
   				}*/
   			}
   		});
   		return false;
    	
    	});
    
    function currencyFormat(num) {           
            if( isNaN( parseFloat( num) ) ) return;
            formatted = parseFloat(num).toFixed(2);
            return formatted; 
    }  ;



});


