var preselect_machine_type = null;
var preselect_machine_make = null;
var preselect_machine_model = null;
	
$(document).ready(function() {

  // apply css3 styles
  $("#content h1").addClass('rounded5');

  // checkout addresses
  $("#stored_invoice").change(function() {
    AddressAutofill($(this).val(), 'invoice');
  });
  if ($("input[name='invoice_name']").val() == '') {
    $("#stored_invoice option[value='0']").attr('selected', 'selected');
    //console.log($("#stored_invoice").val());
    AddressAutofill($("#stored_invoice").val(), 'invoice');
	}
  $("#stored_delivery").change(function() {
    AddressAutofill($(this).val(), 'delivery');
  });
  if ($("input[name='delivery_name']").val() == '') {
    $("#stored_delivery option[value='0']").attr('selected', 'selected');
    AddressAutofill($("#stored_delivery").val(), 'delivery');
	}
	
	/*
	DISBALED UNTIL UNUSUAL SPEED ISUE IS RESOLVED
	$("a.imagepopup_notitle").fancybox({
		'titleShow': false,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic'
	});
	*/
	
	// account login
	/*
	DISABLED BECUASE IT KILLED BROWSER AUTO-COMPLETE
	$("#widget_username,#widget_password").prev('label').hide();
	$("#widget_username").addClass('widget_autofill');
	$("#widget_username").val('Email address');
	$("#widget_username").focus(function() {
		if ($(this).val() == 'Email address') {
			$(this).removeClass('widget_autofill');
			$(this).val('');
		}
	});
	$("#widget_username").blur(function() {
		if ($(this).val() == '') {
			$(this).addClass('widget_autofill');
			$(this).val('Email address');
		}
	});
	$("#widget_password").before('<input type="text" id="widget_password_help" class="widget_autofill" value="Password" />');
	$("#widget_password").hide();
	$("#widget_password_help").live('focus', function() {
		$(this).hide();
		$("#widget_password").show();
		$("#widget_password").focus();
	});
	$("#widget_password").blur(function() {
		if ($(this).val() == '') {
			$("#widget_password").hide();
			$("#widget_password_help").show();
		}
	});
	*/
	
	// on load notice
	//if ($("#notice").html().length > 0) {
	if ($("#notice").length > 0) {
		$("#notice").addClass('animated');
		setTimeout("HideAlert()", 6000);
	}

	if ($("#widget_brands")){
	  $("#widget_brands").remove();
	  $("#widget_brands_submit").remove();
	  $("#f_search_brands").append('<input type="text" name="brand" id="widget_brands_ajax_search" value="" />');
	  $("#widget_brands_ajax_search").autocomplete({
	    "source": "/ajax/brandsearch/",
	    "delay": 100,
	    "minLength": 2,
	    select: function(event, ui){
	      $("#widget_brands_ajax_search").val(ui.item.value);
	      $("#f_search_brands").submit();
	    }
	  });
	}

  if ($("#cat_results_filter")){
    $("#cat_results_filter input[type=submit]").hide();
    $("#cat_results_filter select").change(function(){
      $("#cat_results_filter form").submit();
    });
  }
  
  $("#requisition_pad").change(function(){
    $("#edit-requisition-pad input[type=submit]").trigger('click');
  });
  
  $("#del-requisition-pad .delete, #requisition-pad-items a.delete").click(function(){
    if (confirm('Are you sure you wish to delete this?')){
      return true;
    }
    return false;
  });
  
  $('<p style="margin:0; margin-top:15px;"><label><input type="checkbox" value="" id="hide-images" />Hide Images</label></p>').insertBefore("#requisition-pad-items-form");
  $("#requisition-pad-items").css('marginTop', '0px');
  var hiddenImages = false;
  $("#hide-images").live('click', function(){
    if (hiddenImages == false){
      $("#requisition-pad-items img").hide('slow');
      hiddenImages = true;
    }else{
      $("#requisition-pad-items img").show('slow');
      hiddenImages = false;
    }
  });
  
  $("#favourite a").not('.favourite').attr('target', '_blank');
	
	// budget elements
	if($("#ordering_auth").val() != 'limit') {
		$("#credit_limit").hide();
	}
	$("#ordering_auth").change(function() {
		if($(this).val() == 'limit') {
			$("#credit_limit").show();
		} else {
			$("#credit_limit").hide();
		}
	});
	if($("#credit_limit_override").val() != 1) {
		$("#credit_limit_custom").hide();
	}
	$("#credit_limit_override").change(function() {
		if($(this).val() == 1) {
			$("#credit_limit_custom").show();
		} else {
			$("#credit_limit_custom").hide();
		}
	});
	
	// checkout cost centres
	$("#defualt_cc").show();
	cost_center_override($(".checkout_line_options:first select").val());
	$("#defualt_cc select").change(function() {
		if ($(this).val() != '0') {
			$(".checkout_line_options select").val($(this).val());
		}
	});
	$(".checkout_line_options select").change(function() {
		cost_center_override($(this).val());
	});
	
	$("#buyer_level").change(function() {
		ChangeUserLevel();
	});
	if ($("#buyer_level").length ) {
		ChangeUserLevel();
	}
	
	if ($("#allowed_costcentres_option").length) {
		if ($("#allowed_costcentres_option").val() == 'all' || $("#buyer_level").val() != 4) {
			$("#allowed_costcentres_list").hide();
		} else {
			$("#allowed_costcentres_list").show();
		}
		$("#allowed_costcentres_option").change(function() {
			if ($(this).val() == 'all') {
				$("#allowed_costcentres_list").hide();
			} else {
				$("#allowed_costcentres_list").show();
			}
		});
	}
	
	if ($("#buyer_auths_option").length) {
		if ($("#buyer_auths_option").val() == 'all' || $("#buyer_level").val() != 4) {
			$("#buyer_auths_list").hide();
		} else {
			$("#buyer_auths_list").show();
			console.log('dfdsfsdf');
		}
		$("#buyer_auths_option").change(function() {
			if ($(this).val() == 'all') {
				$("#buyer_auths_list").hide();
			} else {
				$("#buyer_auths_list").show();
				console.log('dfdsfsdf');
			}
		});
	}
	
	
	
	$("#f_cartridge_finder").change(function(){
		var type = $("#f_cartridge_finder .type select").val();
		var make = $("#f_cartridge_finder .manufacturer select").val();
		var model = $("#f_cartridge_finder .model select").val();
		$.post('/ajax/cartridges/', $(this).serialize(), function(data){
			if (data.manufacturers){
				$("#f_cartridge_finder .manufacturer select").html('<option value=""> -- Machine Make -- </option>');
				$.each(data.manufacturers, function(e){
					$("#f_cartridge_finder .manufacturer select").append('<option value="' + data.manufacturers[e] + '">' + data.manufacturers[e] + '</option>');
				});
				$("#f_cartridge_finder .manufacturer select").val(make);
				$("#f_cartridge_finder .manufacturer").show();
				$("#f_cartridge_finder .model select").html('<option value=""> -- Machine Model -- </option>');
			}
			
			if (data.models){
				$("#f_cartridge_finder .model select").html('<option value=""> -- Machine Model -- </option>');
				$.each(data.models, function(e){
					$("#f_cartridge_finder .model select").append('<option value="' + data.models[e] + '">' + data.models[e] + '</option>');
				});
				$("#f_cartridge_finder .model select").val(model);
				$("#f_cartridge_finder .model").show();
			}
			
			// preselect make if apropriate
			if (preselect_machine_make) {
				$("#supplies_make").val(preselect_machine_make);
				$("#f_cartridge_finder").change();
				preselect_machine_make = null;
			}
			
			// preselect model if apropriate
			else if (preselect_machine_model) {
				$("#supplies_model").val(preselect_machine_model);
				preselect_machine_model = null;
			}
			
			if (data.codes){
				var url = '/supplies/'+urlencode(type)+'/'+urlencode(make)+'/'+urlencode(model)+'/';
				document.location = url;
				/*
				no longer redirects to search page
				var str='';
				$.each(data.codes, function(e){
				if (e > 0){
				str += "&";
				}
				str += "find[]=" + data.codes[e];
				});
				document.location = '/search/?' + str;
				*/
			}
			
		}, 'json');
	});
	
});

function cost_center_override(test_val) {
	var all_same = true;
	$(".checkout_line_options select").each(function() {
		if ($(this).val() != test_val) {
			all_same = false;
		}
	});
	if (all_same) {
		$("#defualt_cc select").val(test_val);
	} else {
		$("#defualt_cc select").val('0');
	}
}


function ChangeUserLevel() {
	var newlevel = $("#buyer_level").val();
	//console.log(newlevel);
	
	// show prices
	if (newlevel == 1 || newlevel == 2 || newlevel == 3) {
		$("#buyer_prices").parent().hide();
	} else {
		$("#buyer_prices").parent().show();
	}
	
	// force req. pad
	if (newlevel == 3) {
		$("#buyer_reqpad").parent().hide();
		$("#buyer_reqpad_auth").parent().show();
	} else if (newlevel == 4) {
		$("#buyer_reqpad").parent().show();
		$("#buyer_reqpad_auth").parent().hide();
	} else {
		$("#buyer_reqpad").parent().hide();
		$("#buyer_reqpad_auth").parent().hide();
	}
	
	// allowed cost centres
	if ($("#allowed_costcentres_list").length) {
		if (newlevel == 4) {
			$("#allowed_costcentres_option").parent().show();
		} else {
			$("#allowed_costcentres_option").parent().hide();
			$("#allowed_costcentres_list").hide();
		}
	}
	
	// allowed authorisers
	if ($("#buyer_auths_list").length) {
		if (newlevel == 4) {
			$("#buyer_auths_option").parent().show();
		} else {
			$("#buyer_auths_option").parent().hide();
			$("#buyer_auths_list").hide();
		}
	}
	
	// ordering rules
	var show_budget = true;
	if (newlevel == 1 || newlevel == 2 || newlevel == 3 || newlevel == 5) {
		show_budget = false;
		$("#ordering_auth").parent().hide();
		$("#ordering_auth option[value='always']").removeAttr('disabled');
		$("#ordering_auth option[value='limit']").removeAttr('disabled');
		$("#ordering_auth option[value='auth']").removeAttr('disabled');
	} else if (newlevel == 4) {
		$("#ordering_auth").parent().show();
		$("#ordering_auth option[value='always']").removeAttr('disabled');
		$("#ordering_auth option[value='limit']").removeAttr('disabled');
		$("#ordering_auth option[value='auth']").removeAttr('disabled');
	}
	if(show_budget && $("#ordering_auth").val() == 'limit') {
		$("#credit_limit").show();
	} else {
		$("#credit_limit").hide();
	}
	
}


function HideAlert() {
	$('#notice').animate({
		opacity: 0,
		height: 'toggle'
	}, 1500);
}

function AddressAutofill(id, type) {
	$.post('/ajax/autocomplete/', {
	  'type' : type,
		'id' : id
	}, function(data) {
		$("input[name='"+data.type+"_name']").val(data.name);
		$("input[name='"+data.type+"_street1']").val(data.street1);
		$("input[name='"+data.type+"_street2']").val(data.street2);
		$("input[name='"+data.type+"_town']").val(data.town);
		$("input[name='"+data.type+"_county']").val(data.county);
		$("input[name='"+data.type+"_post_code']").val(data.post_code);
		$("input[name='"+data.type+"_contact']").val(data.contact);
		$("input[name='"+data.type+"_phone']").val(data.phone);
		if (data.type == 'delivery') {
			$("textarea[name='"+data.type+"_instructions']").val(data.instructions);
		}
	}, 'json');
}

function AddMultiToBasket() {
	var prods = '';
	$(".qty_input").each(function() {
		if ($(this).val() != 0 && $(this).val() != '') {
			prods += $(this).attr('name') + '|' + $(this).val() + ',';
		}
	});
	if (prods.length) {
		$.post('/basket/bulk-add/', {
			'products': prods.substring(0, prods.length-1)
		}, function(data) {
			//console.log(data);
			if (data == 'ok') {
				// redirect to basket
			    $.get('/ajax/basketsummary/', function(data){
			    	if (data.items == 1) {
			      		$('#widget_basket_items').text(data.items + ' item');
			    	} else {
			      		$('#widget_basket_items').text(data.items + ' items');
			    	}
			      $('#widget_basket_total').text(data.value);
			    }, 'json');
				alert('Your basket has been updated.');
			} else {
				alert('Please check your quantities.');
			}
		}, 'json');
	} else {
		alert('Nothing to add. Please check your quantities.');
	}
}

function AddToBasket(form, img){

  var $img = $('#p-'+img);
  var imgPos = $img.offset();
  var $newImg = $img.clone().removeAttr('id');
  var $basket = $('div.basketsummary');
  var basketPos = $basket.offset();
  
  //alert(basketPos.left);
  //alert(basketPos.top);
  
  $newImg.css({
    'left': imgPos.left+'px',
    'top': imgPos.top+'px',
    'position': 'absolute',
    'zIndex': 999
  })
  .prependTo('body')
  .animate({
    'left': (basketPos.left) + 'px',
    'top': (basketPos.top) + 'px',
    'width': (parseInt($newImg.width()) / 2) + 'px',
    'height': (parseInt($newImg.height()) / 2) + 'px',
    'opacity': 0
  }, 1000, function(){
    $(this).remove();
  });
  
  $.post($(form).attr('action'), {
    'quantity': $(form).find('input[name=quantity]').val()
  }, function (data){
    $.get('/ajax/basketsummary/', function(data){
    	if (data.items == 1) {
      		$('#widget_basket_items').text(data.items + ' item');
    	} else {
      		$('#widget_basket_items').text(data.items + ' items');
    	}
      $('#widget_basket_total').text(data.value);
    }, 'json');
  });
  
  return false;
}

function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();

    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
