$(window).load(function(){
    //If a cookie is set, adjust the shipping address dropdowns to show current value
    if($.cookie('location') && $.cookie('location')!='none'){
        var location = $.cookie('location');
        $('#DeliveryCountry').val(location).attr('selected','selected');
        //specifically for customer details page
        $('input[name=d_country]').val(location);
        var country = $('#DeliveryCountry option:selected').text();
        $('#d_country').val(country);
    }else{
        $('#DeliveryCountry').val('GB').attr('selected','selected');
    }
});

$(document).ready(function(){
	//make li elements into clickable links 
	$('li:has(a)').click( function(){
		var a = $("a",this).attr('href');
		window.location = a;
	});
	
	//now change the cursor when they are hovered
	$('li:has(a)').hover(function() {
		$(this).css('cursor','pointer');
		}, function() {
		$(this).css('cursor','auto');
	});
	
    //Set the shipping location from the side panel
    $('#shipping-set').click(function(){
       var country = $('#DeliveryCountry').val();
       $.cookie("location",country);
       $(document).refresh();
    });
    
    //Sends the contact form
    $('#contact-form').submit(function(){
      name = $('#name').val();
      email = $('#email').val();
      message = $('#message').val();
      $.post("/welcome/send_contact_form", {"name" : name, "email" : email, "message" : message},
      function(data){
          $('#return-message').html(data['return_message']);
          $('#return-message').show();
       },
       "json");
       return false;
    });
    
    //Sends the mini contact form
    $('#mini-contact-form').submit(function(){
      msg_type = $('#msg_type option:selected').val();
      return_email = $('#return_email').val();
      mini_message = $('#mini_message').val();      
            
            $.post("/welcome/mini_contact_form", {"msg_type" : msg_type, "return_email" : return_email, "mini_message" : mini_message},
            function(data){
               alert(data['return_message']);
               if(data['return_value']==1){
               		$('#return_email').val("");
      				$('#mini_message').val("");
               }
             },
             "json");  
       return false;
    });
    
    //Instant search suggestions
    $('input[name=query]').keyup(function(){
        $('#search-suggestions li').remove();
        query = $('input[name=query]').val();
        if(query.length > 2){
            $.post("/catalogue/search_suggestions", {"query" : query},
            function(data){
                jQuery.ajaxSetup({async:false});
                jQuery.each(data['results'],function(){
                   $('#search-suggestions ul').append("<li><a href=\"/catalogue/product/"+this['product_id']+"/"+this['product_filename']+"\" >"+this['product_name'].substr(0, 20)+"...</a></li>");
                });
                $('#search-suggestions').show();
                return true;
            },
            "json");
        }
    });
    
    $('input[name=query]').blur(function(){
        $('#search-suggestions').fadeOut(200);
    });
    
    //Check if customer accepts terms and conditions
    $('.check-agreement').click(function(){

     if($('input:checkbox[name=agreement]').is(':checked')){
        return true;
     }
     alert('You must accept the terms and conditions before continuing.');
     return false;
    });
    
    //Customer details form autofill delivery
    $('#delivery_same').click(function(){
       if($('#delivery_same').is(':checked')){
           $('input[name=d_first_name]').val($('input[name=first_name]').val()).attr('disabled','disabled');
           $('input[name=d_surname]').val($('input[name=surname]').val()).attr('disabled','disabled');
           $('input[name=d_address1]').val($('input[name=address1]').val()).attr('disabled','disabled');
           $('input[name=d_address2]').val($('input[name=address2]').val()).attr('disabled','disabled');
           $('input[name=d_city]').val($('input[name=city]').val()).attr('disabled','disabled');
           $('input[name=d_postcode]').val($('input[name=postcode]').val()).attr('disabled','disabled');
           $('input[name=d_phone]').val($('input[name=phone]').val()).attr('disabled','disabled');

       }else{
           $('input[name=d_first_name]').removeAttr('disabled');
           $('input[name=d_surname]').removeAttr('disabled');
           $('input[name=d_address1]').removeAttr('disabled');
           $('input[name=d_address2]').removeAttr('disabled');
           $('input[name=d_city]').removeAttr('disabled');
           $('input[name=d_postcode]').removeAttr('disabled');
           $('input[name=d_phone]').removeAttr('disabled');

       }
       

    });
    
    $('#customer-form').submit(function(e){
        if(checkform()){
            return true;
        }else{
            e.preventDefault();
        }
    });
    
    //star rating code
     $('input.star').rating({            
           callback: function(value, link){
               if($('input.star').attr('disabled')=='disabled'){
                alert('You already rated this product');
                return false;
               }
               prodid = $('input[name=prodid]').val();
               $.post("/catalogue/update_rating", {"prodid" : prodid, "rating" : value},
            function(data){
                $('input[name=star1]').attr('disabled',true);
                $('#average-score').html('Average score <b>'+data['rating']+'</b>/5. Based on '+data['num_ratings']+' review(s).');
            },
            "json");
          }
    });
});

function checkform(){
    
	if (!document.customerform.BillingFirstnames.value) {
			alert('You haven\'t filled in your billing name!');
			document.customerform.BillingFirstnames.focus();
			return false;
		
	}
	else if (!document.customerform.BillingSurname.value) {
			alert('You haven\'t filled in your billing surname!');
			document.customerform.BillingSurname.focus();
			return false;
		
	}
	else if (!document.customerform.BillingAddress1.value) {
			alert('You haven\'t filled in your billing address!');
			document.customerform.BillingAddress1.focus();
			return false;
		
	}
	else if (!document.customerform.BillingCity.value) {
			alert('You haven\'t filled in your billing city!');
			document.customerform.BillingCity.focus();
			return false;
		
	}
	else if (!document.customerform.BillingPostCode.value) {
			alert('You haven\'t filled in your post code!  If you don\'t have a Post Code enter 0000 into the box.');
			document.customerform.BillingPostCode.focus();
			return false;
		
	}
	else if (!document.customerform.BillingCountry.value) {
			alert('You haven\'t selected your country!');
			return false;
		
	}
	else if (!document.customerform.BillingPhone.value) {
			alert('You haven\'t filled in your phone number!  We need this to contact you if theres a problem with your order.');
			document.customerform.BillingPhone.focus();
			return false;
		
	}
	else if (!document.customerform.CustomerEMail.value) {
			alert('You haven\'t filled in your e-Mail address!  We need this to send you your recepit or contact you about your order.');
			document.customerform.CustomerEMail.focus();
			return false;
		
	}
        else if (!document.customerform.CustomerEMailVerify.value) {
			alert('We need you to retype your e-Mail address to avoid mistakes which could prevent us from contacting you.');
			document.customerform.CustomerEMailVerify.focus();
			return false;
        }
        if(checkEMail(document.customerform.CustomerEMail.value)==false){
                        alert('The e-Mail address you provided was not valid.  Please check and try again.');
                        document.customerform.CustomerEMail.focus();
			return false;
        }
        if(document.customerform.CustomerEMailVerify.value != document.customerform.CustomerEMail.value){
                        alert('The e-Mail addresses you typed did not match.  Please check and try again.');
                        document.customerform.CustomerEMail.focus();
			return false;
        }
        
        if (!document.customerform.DeliveryFirstnames.value) {
			alert('You haven\'t filled in your delivery name!');
			document.customerform.DeliveryFirstnames.focus();
			return false;
		
	}
	else if (!document.customerform.DeliverySurname.value) {
			alert('You haven\'t filled in your delivery surname!');
			document.customerform.DeliverySurname.focus();
			return false;
		
	}
	else if (!document.customerform.DeliveryAddress1.value) {
			alert('You haven\'t filled in your delivery address!');
			document.customerform.DeliveryAddress1.focus();
			return false;
		
	}
	else if (!document.customerform.DeliveryCity.value) {
			alert('You haven\'t filled in your delivery city!');
			document.customerform.DeliveryCity.focus();
			return false;
		
	}
	else if (!document.customerform.DeliveryPostCode.value) {
			alert('You haven\'t filled in your delivery post code!  If you don\'t have a Post Code enter 0000 into the box.');
			document.customerform.DeliveryPostCode.focus();
			return false;
		
	}
	else if (!document.customerform.DeliveryPhone.value) {
			alert('You haven\'t filled in your delivery phone number!  We need this to contact you if theres a problem with your order.');
			document.customerform.DeliveryPhone.focus();
			return false;
		
	}
	return true;
}

function checkEMail(address)
{
var atpos=address.indexOf("@");
var dotpos=address.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=address.length)
  {
  return false;
  }
}
