$(document).ready(function(){
	  $('form').each(function() {
			var formId = $(this).attr('id');
			$('a[rel="'+formId+'clear"]').unbind('click').bind('click', function() {
				$('#'+formId).find(':input').each(function() {
					switch(this.type) {
			            case 'password':
			            case 'select-multiple':
			            case 'select-one':
			            case 'text':
			            case 'textarea':
			                $(this).val('');
			                break;
			            case 'checkbox':
			            case 'radio':
			            	if($(this).closest('ul').hasClass('dpl-selector')) break; 
			                this.checked = this.defaultChecked;
			        }
					$(this).closest('li').find('.errors').hide();
				});
				
				return false;
			});

			$('a[rel="'+formId+'reset"]').unbind('click').bind('click', function() {$('#'+formId).first().reset(); return false;});
			$('a[rel="'+formId+'submit"]').unbind('click').bind('click', function() {$('#'+formId).first().submit(); return false;});
		  });

	  // Submit form if focus on inputfields and enter is pressed
	  // To handle autocomplete, we disable next enter if arrow up/down pressed and autocomplete is not turned off 
	  $('form input:text, form input:password').keyup(function(e){
	    var arrowKeys = new Array(38, 40);
	    var key = e.charCode || e.keyCode || 0;
	    if(key == 13){
	        if($(this).data('entersubmit')) {
	            e.preventDefault(); 
	            $(this).closest('form').submit();
	            return false;
	        }
	        $(this).data('entersubmit', true);
	    } else if($.inArray(key, arrowKeys) > -1) {
	        if($(this).attr('autocomplete') != 'off') {
	            $(this).data('entersubmit', false);
	        }
	    }
	  })
	  .blur(function(){
	      $(this).data('entersubmit', true);
	  }) 
	  .focus(function(){
	      $(this).data('entersubmit', true);
	  });
	  
	  $('.box .close').click(function() {
			 $(this).closest('div.box').hide(); 
		  });

	  $('#nav-primary li a').each(function() {
		  var href = $(this).attr('href');
		  var curPath = window.location.pathname;
		  if(curPath.substr(0, href.length) == href) {
			  $(this).closest('li').addClass('active');
			  return false;
		  }
	  });

	  $('#nav-tertiary li a').each(function() {
		  var href = $(this).attr('href');
		  var curPath = window.location.pathname;
		  if(curPath == href) {
			  $(this).closest('li').addClass('active');
			  return false;
		  }
	  });
	  
	  $('input.qty').qty();
	  $('input.numeric').numeric();
	    
	  $('a.disabled').live('click', function(){ return false; });

	  $("form label.required").not("h5 label").prepend('<span></span>');

	  $(".caps-sense").each(function() {
		  $(this).wrap('<span></span>').parent().append('<div class="caps-notice"><div>Caps Lock<div class="end"></div></div></div>');
	  }).capslock({
			caps_lock_on: function() {
		  		$(this).parent().find('.caps-notice').show();
			},
			caps_lock_off: function() {
				$(this).parent().find('.caps-notice').hide();
			}
		}).blur(function() {
			$(this).parent().find('.caps-notice').hide();
		});	 
	  
	  $("form div.element ul.errors").each(function() {
			 $(this).closest('li').addClass('has-errors'); 
			 $(this).closest('form').addClass('has-errors'); 
		  });
		  
		  $(".if-js-show").removeClass('if-js-show').show();
		  $(".if-js-hide").hide();
		  
		  // Open external links in new window
		  $('a[rel*="external"]').each(function(){
		    $(this).attr('target','_blank');
		  });

		  $('a[rel*="printdialog"]').click(function(){
			  window.print();
			  return false;
		  });

		  // Open external links in new window
		  $('a[rel*="popup"]').each(function(){
		    $(this).colorbox({width: '60%', height: '80%', rel: 'nofollow'});
		  });

		  // Open youtube links in new window
		  $('a[rel*="youtube"]').live('click', function(){
			  $.colorbox({iframe:true, innerWidth:700, innerHeight:450, href:$(this).attr('href')});
			  $('#cboxClose').hide();
			  return false;
		  });
	
		  // Open images in new window
		  $('a[rel*="gallery"]').colorbox({innerHeight:600});

		  
  $(".scrollable").each(function(i) {
	if($(this).find('.item').length > 1) {
      $(this).scrollable({circular: true, vertical: false})
             .autoscroll({interval: 6000})
             .navigator({navi: ".scrollable-navi"});
	  if($(this).parent('#front-ads').length) {
		 $(this).find('.item').hide();		  
		 $(this).find('.first').addClass('active').show();	 
		 api = $(this).scrollable();
		 conf = api.getConf();
		 conf.speed = 0;
		 api.onBeforeSeek(function(event,index){
			 	items = api.getItems();
			 	$(items[index]).fadeTo(0, 0).css('zIndex', '2');
			 	previous = api.getRoot().find('.active').css('zIndex', '1').removeClass('active');
			 	$(items[index]).addClass('active').fadeTo("slow", 1);
			 	if($(items[index]).hasClass('express-valid')) {
			 		$('#front-ads div.express').hide();
			 	} else {
			 		$('#front-ads div.express').show();
			 	}
			 	if(index < items.length) {
			 		previous.fadeTo("slow", 0);
			 	}
			});
	  }
	}
  });

  $('#subscribe-email').focus(function() {
	  if($(this).val() == $(this).attr('defaultValue')) {
		  $(this).val('');
	  }
  })
  .blur(function() {
	  if($(this).val() == '') {
		  $(this).val($(this).attr('defaultValue'));
	  }
  }).closest('form').submit(function() {
	  if($(this).find('#subscribe-email').val() == '' || $(this).find('#subscribe-email').val() == $(this).find('#subscribe-email').attr('defaultValue')) {
		  return false;
	  }
  });
  
	if(jQuery.fn.scrollFollow) {
		$('.scroll-follow').each(function() {
			var container = $(this).closest('.scroll-follow-relative');
			if(container.length == 0) {
				container = $(this).parent();
			}
			$(this).scrollFollow({'container': container, 'offset': 20 });
		});
	}
  
	
	$('#locationaddressform-user_location_type').change(function() {
		if($('#address-type-' + this.value + '-pane').length) {
			$('.address-type-pane').hide();
			$('#address-type-' + this.value + '-pane').show();
			adjustLocationTypeDescriptionHeight();
		}
	});
	
	$('#timeorderform-date').datepicker({
		minDate: '0',
		maxDate: '+21D',
		dateFormat: 'dd-mm-yy',
		showAnim: 'slideDown',
	    buttonImage: '/img/calendar.png',
	    showOn: 'both',
		buttonImageOnly: true
	    
	}).attr('autocomplete', 'off');
	
	$('#locationaddressform-identity_birthday').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '-90:-13',
		minDate: '-90Y',
		maxDate: '-13Y',
		defaultDate: '-30Y',
		dateFormat: 'dd-mm-yy',
		showAnim: 'slideDown'
	}).attr('autocomplete', 'off');

	$('#kidsclubform-identity_birthday').datepicker({
		changeMonth: true,
		changeYear: true,
		yearRange: '-13',
		minDate: '-13Y',
		maxDate: '+0D',
		defaultDate: '-6Y',
		dateFormat: 'dd-mm-yy',
		showAnim: 'slideDown'
	}).attr('autocomplete', 'off');
	
	$('#locationaddressform-houseForm-zipcode_value').zipcode({city: '#locationaddressform-houseForm-zipcode_city'});
	$('#locationaddressform-apartmentForm-zipcode_value').zipcode({city: '#locationaddressform-apartmentForm-zipcode_city'});
	$('#locationaddressform-businessForm-zipcode_value').zipcode({city: '#locationaddressform-businessForm-zipcode_city'});
	$('#locationaddressform-dormitoryForm-zipcode_value').zipcode({city: '#locationaddressform-dormitoryForm-zipcode_city'});
	$('#locationaddressform-otherForm-zipcode_value').zipcode({city: '#locationaddressform-otherForm-zipcode_city'});
	
	$('#locationaddressform-identity_cellphone').after($('.use-identity-as-cellphone'));
	
	$('.use-identity-as-cellphone').removeClass('hidden').click(function() {
		$('#locationaddressform-identity_cellphone').val($('#locationaddressform-credentialForm-user_identity').val());
		return false;
	});
	
	adjustLocationTypeDescriptionHeight();
	
});

var ajaxi = 0;
var pizzaTrackerTimer;
var pizzaTracker = function(tracker, customerId, orderId, step, options) {
	
	var settings = jQuery.extend({
		type: 'delivery',
		s1: { duration: 6, pulseTime: 1500 },
		s2: { duration: 6, pulseTime: 1500 },
		s3: { duration: 7, pulseTime: 1500 },
		s4: { duration: 2, pulseTime: 1500 },
		s5: { duration: 10, pulseTime: 1500, effect: 'slide' }
	}, options);

	if(!settings.directInput) {
		customerIdElm = $(customerId);
		orderIdElm = $(orderId);
		if(!$(tracker).length || !customerIdElm.length || !orderIdElm.length) {
			alert('ERROR: Incorret implentation');
			return false;
		}

		customerId = customerIdElm.val();
		orderId = orderIdElm.val();
	}		
	
	if(step == undefined) {
		step = 0;
	}
	
	var inputError = false;
	if(customerId.length != 8) {
		openDialog('Indtast dit telefon nr.', 'Dit telefon nr. skal være 8 cifre.');
		return false;
	}
	if(orderId.length != 15 && orderId != '0') {
		openDialog('Indtast dit tracking nr.', 'Dit tracking nr. skal være 15 cifre.');
		return false;
	}

	$.ajax({
		url: "/async/order-info/",
		dataType: "json",
		cache: false,
		data: { q: customerId + '-' + orderId },
		success: function( data ) {
			if(data.error == 'no-info') {
				pizzaTrackerNoInfo(tracker);
				return false;
			} 

			if(settings.successCallback) {
				settings.successCallback(data);
			}

			if($(tracker).length == 0) {
				pizzaTrackerTimer = setTimeout(function() { pizzaTracker(tracker, customerId, orderId, step, options); } , 1000);
				return false;
			}
			
			$(tracker).find('.t5 span').hide();
			$(tracker).find('.t5 .' + data.type).show();
			
			var nextStep = step;
			if(data.type == 'pickup') {
				settings.s5.effect = 'pulsate';
				
				if(parseInt(data.canceled) > 0) {
					nextStep = -2;
				} else if(parseInt(data.h_id) > 0) {
					nextStep = -1;
				} else if(data.away > 0) {
					nextStep = 5;
				} else if(data.oven > 0) {
					nextStep = 2;
				} else if(data.sent > 0) {
					nextStep = 1;
				}
			} else {
				settings.s5.effect = 'slide';
				
				if(parseInt(data.canceled) > 0) {
					nextStep = -2;
				} else if(parseInt(data.h_id) > 0) {
					nextStep = -1;
				} else if(data.delivered > 0) {
					nextStep = 5;
				} else if(data.away > 0) {
					nextStep = 4;
				} else if(data.oven > 0) {
					nextStep = 2;
				} else if(data.sent > 0) {
					nextStep = 1;
				}
			}

			nowDate = new Date();
			jsTs = nowDate.getTime() / 1000;
			serverDiff = data.timestamp - jsTs;

			if(step != nextStep) {
				if(nextStep == 2) {
					oventime = settings['s' + (0+ nextStep + 1)].duration * 60;
					oventimeLeft = data.oven+oventime - data.timestamp;
 
					settings['s' + (0+ nextStep + 1)].duration = oventimeLeft / 60;
					settings['s' + (0+ nextStep + 1)].progress = Math.max(0, Math.min(100, (100 - ((100/(oventime/oventimeLeft)))))); 
					
					setTimeout(function() { pizzaTrackerStep(tracker, nextStep+1, settings['s' + (0+ nextStep + 2)]); } , (settings['s' + (0+ nextStep + 1)].duration * 60 * 1000));
					if(data.type == 'pickup') {
						settings['s' + (0+ nextStep + 3)].effect = 'pulsate';
						setTimeout(function() { pizzaTrackerStep(tracker, nextStep+2, settings['s' + (0+ nextStep + 3)]); } , ((settings['s' + (0+ nextStep + 1)].duration+settings['s' + (0+ nextStep + 2)].duration) * 60 * 1000));
					}
				} else if(nextStep == 4 && data.type == 'delivery') {
					deliverytime = data.quote-data.away;
					deliverytimeLeft = data.quote-data.timestamp;
					
					settings['s' + (0+ nextStep + 1)].duration = deliverytimeLeft / 60;
					settings['s' + (0+ nextStep + 1)].progress = Math.max(0, Math.min(100, (100 - ((100/(deliverytime/deliverytimeLeft))))));
				}
				pizzaTrackerStep(tracker, nextStep, settings['s' + (0+ nextStep + 1)]);
			}
			pizzaTrackerTimer = setTimeout(function() { pizzaTracker(tracker, customerId, orderId, nextStep, options); } , 3000);

		},
		error: function() {
			if(settings.successCallback) {
				settings.successCallback(data);
			}

			pizzaTrackerNoInfo(tracker);
		}
		
	});
	
};

var pizzaTrackerNoInfo = function(tracker) {
	openDialog('Ukendt bestilling', 'Der er ikke foretaget bestillinger på dette telefon nummer i dag.');
};

var pizzaTrackerStep = function(tracker, step, options) {
	$(tracker).each(function() {
		$(this).removeClass('s0 s1 s2 s3 s4 s5');
		if(step >= 0 && step <= 5) {
			$(this).addClass('s' + step);
		}
		for(c = 1; c <= 5; c++) {
			$(this).find('.p' + c + ', .l' + c).each(function() {
				$(this).stop(true, true);
				if(c > step) {
					$(this).hide();
				} else {
					$(this).fadeIn().css('opacity', 1);
				}
			});			
		}
		
		if(step > 0 && step < 5) {
			var pulseTime = 1500;
		    var duration = options.duration * 60 * 1000;
			var pulsations =  duration / pulseTime;
			
			$(this).find('.l' + (0+step+1)).effect("pulsate", { times:pulsations }, pulseTime);
		}
		// Animations
		switch(step) {
		    case -2:
		    	openDialog('Annulleret', 'Butikken har annulleret din bestilling. Har du spørgsmål er du velkommen at ringe til vores CallCenter på telefon <b>33-123456</b>.');
		    	break;
		    case -1:
		    	openDialog('Ubekræftet', 'Butikken har endnu ikke bekræftet din ordre, hav venligst din telefon klar i tilfælde af vi ringer.<br /><br />Vent venligst....');
		    	break;
		    case 0:
			case 1:
			case 3:
				$(this).find('.p' + (0+step+1)).effect("pulsate", { times:pulsations }, pulseTime);
				break;
			case 2:
				var ob = $(this).find('.p' + (0+step+1));
				var progress = 0 + options.progress;
				var orgWidth = ob.width();
				var initWidth = ob.height()-5;
				var curWidth = (orgWidth-initWidth)*(progress/100);
				ob.css({width: curWidth + initWidth + "px", display: 'block'}).animate({width: orgWidth + "px"}, duration, 'linear');
				break;
			case 4:
				if(options.effect == 'pulsate') {
					$(this).find('.p' + (0+step+1)).effect("pulsate", { times:pulsations }, pulseTime);
				} else {
					var progress = 0 + options.progress; 
					var ob = $(this).find('.p' + (0+step+1));
					var orgWidth = ob.width();
					var curWidth = (orgWidth-18)*(progress/100);
					ob.css({width: curWidth + 18 + "px", display: 'block'}).animate({width: orgWidth + "px"}, duration, 'linear');
				}
				break;
			case 5:
				break;
			default:
				break;
		}
		
	});
};

function adjustLocationTypeDescriptionHeight() {
	ltd = $('li.location-type .description');
	lt = $('li.location-type');
	vatp = $('.address-type-pane:visible');
	
	newHeight = lt.outerHeight()+vatp.outerHeight();
	ltd.height(newHeight);
}

var zipcodeCache = {};
jQuery.fn.zipcode = function(options) {
	var settings = jQuery.extend({
		minLength: 2,
		source: function(request, response) {
			if ( request.term in zipcodeCache ) {
				response( zipcodeCache[ request.term ] );
				return;
			}
			
			$.ajax({
				url: "/async/zipcode/",
				dataType: "json",
				data: { q: request.term },
				success: function( data ) {
					zipcodeCache[ request.term ] = data;
					response( data );
				}
			});
		},
		focus: function(event, ui) {
			$(settings.element).val(ui.item.zipcode);
			$(settings.city).val(ui.item.city);
			return false;
		},
		select: function(event, ui) {
			$(settings.element).val(ui.item.zipcode);
			$(settings.city).val(ui.item.city);
			return false;
		},
		city: false,
		selectFirst: true
	}, options);

	return this.each(function(){
			settings.element = $(this);
			$(this).autocomplete(settings).data("autocomplete")._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.zipcode + " " + item.city + "</a>" )
				.appendTo( ul );
		};
	});
};

var streetCache = {};
jQuery.fn.street = function(options) {
	var settings = jQuery.extend({
		minLength: 2,
		source: function(request, response) {
			if ( request.term in streetCache ) {
				response( streetCache[ request.term ] );
				return;
			}
			
			$.ajax({
				url: "/async/street/",
				dataType: "json",
				data: { q: request.term },
				success: function( data ) {
					streetCache[ request.term ] = data;
					response( data );
				}
			});
		},
//		focus: function(event, ui) {
//			$(settings.element).val(ui.item.street + ' ');
//			$(settings.zipcode).val(ui.item.zipcode + ' ' + ui.item.city);
//			return false;
//		},
		select: function(event, ui) {
			$(settings.element).val(ui.item.street + ' ');
			$(settings.zipcode).val(ui.item.zipcode + ' ' + ui.item.city);
			return false;
		},
		zipcode: false,
		selectFirst: false
	}, options);

	return this.each(function(){
			settings.element = $(this);
			$(this).autocomplete(settings).data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a>" + item.street + ", " + item.zipcode + " " + item.city + "</a>" )
				.appendTo( ul );
		};
	});
};

function openDialog(title, message) {
	var $dialog = $('<div></div>')
	.html(message)
	.dialog({
		dialogClass: 'ui-dialog-builder',
		title: title,
		modal: true,
	    closeText: 'Luk | X',
	    draggable: false,
	    resizable: false,
	    buttons: {
			Ok: function() {
				$(this).dialog("close");
			}
		},
		open: function(event, ui) { $(this).parent().find('.ui-button-text').each(function() {
			$(this).wrap('<a class="button secondary small"></a>');
		}); }

	});
}

function checkTime(i) {
	if (i<10) {
		i='0' + i;
	}
	return i;
}

(function($){
    $.fn.numeric  = function(options){
      var opts = $.extend($.fn.numeric.defaults, options);
      return this.each(function(){
        $(this).keydown(function(e){
          var key = e.charCode || e.keyCode || 0;
          if (opts.allowControlKeys && isControlKey(key)){
            return true;
          }
          return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105));
        });
      });
    };
    function isControlKey(key){
      var controlKeys = new Array(8, 9, 13, 46, 37, 38, 39, 40);
      return $.inArray(key, controlKeys) > -1;
    }
    $.fn.numeric.defaults = {allowControlKeys: true};
  })(jQuery);

function ordToString(ordArray){
	var l = ordArray.length;
	var salt = ordArray[0];
	var s = '';
	for(var n=1; n<l; n++){
		s+=String.fromCharCode((0+ordArray[n]-salt));
	}
	return s;
}

(function($){
    $.fn.qty  = function(options){
      var opts = $.extend($.fn.qty.defaults, options);
      return this.each(function(){
    	$(this).attr('autocomplete', 'off');
    	$(this).focus(function(e) {
    		$(this).data('curVal', $(this).val());
    	});
    	$(this).blur(function(e) { 
    		var val = parseInt($(this).val());
    		if(isNaN(val)) {
    			val = $(this).data('curVal');
    		}
    		if($(this).hasClass('not-null') && val == 0) {
    			val = 1;
    		}
			$(this).val(val);    		
    	});
    	$(this).keyup(function(e){
    		var key = e.charCode || e.keyCode || 0;
            var val = parseInt($(this).val().replace(/^0+/, ''));
            if(isNaN(val)) {
          	  val = 0;  
            }
    		if($(this).hasClass('not-null') && val == 0) {
    			val = 1;
    		}
            if(!isNaN(val) && ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 38 || key == 40 || key == 33 || key == 34)) {
	            val = Math.max(opts.minValue, Math.min(opts.maxValue, val));
	            $(this).val(val);
            }
    	});
        $(this).keydown(function(e){
          var key = e.charCode || e.keyCode || 0;
          var val = parseInt($(this).val().replace(/^0+/, '')); 
          if(isNaN(val)) {
        	  val = 0;  
          }
          if(!isNaN(val) && (key == 38 || key == 40 || key == 33 || key == 34)) {
              val = Math.max(opts.minValue, Math.min(opts.maxValue, val));
        	  if(key == 38) {
            	  val++;
              } else if(key == 40) {
            	  val--;
              } else if(key == 33) {
            	  val += 10;
              } else if(key == 34) {
            	  val -= 10;            	  
              }
              val = Math.max(opts.minValue, Math.min(opts.maxValue, val));
      		  if($(this).hasClass('not-null') && val == 0) {
      			val = 1;
    		  }
        	  $(this).val(val);
          } 
          if (opts.allowControlKeys && isControlKey(key)){
            return true;
          }
          return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105));
        });
      });
    };
    function isControlKey(key){
      var controlKeys = new Array(8, 9, 46, 37, 38, 39, 40);
      return $.inArray(key, controlKeys) > - 1;
    }
    $.fn.qty.defaults = {allowControlKeys: true, minValue: 0, maxValue: 99};
  })(jQuery);


//custom easing called "custom"
$.easing.custom = function (x, t, b, c, d) {
	var s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return -10;
	//return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}

(function( $ ) {$( ".ui-autocomplete-input" ).live( "autocompleteopen", function() {	var autocomplete = $( this ).data( "autocomplete" ),		menu = autocomplete.menu;	if ( !autocomplete.options.selectFirst ) {		return;	}	menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );if(menu.element.children().length < 2) { autocomplete.close(); }});}( jQuery ));

(function($) {
    $.fn.capslock = function(options) {
        if (options) $.extend($.fn.capslock.defaults, options);
    	this.each(function() {
			$(this).bind("caps_lock_on", $.fn.capslock.defaults.caps_lock_on); 
			$(this).bind("caps_lock_off", $.fn.capslock.defaults.caps_lock_off); 
			$(this).keypress(function(e){

		    	var ascii_code = e.which;
		    	var shift_key = e.shiftKey; 
		    	if( (65 <= ascii_code) && (ascii_code <= 90) && !shift_key) {
		    		$(e.target).trigger("caps_lock_on"); 
		    	} else if(!shift_key) {
					$(e.target).trigger("caps_lock_off"); 
				}
			});
    	}); 
    	return this;
	};
    $.fn.capslock.defaults = {
    	caps_lock_on: function() {},
    	caps_lock_off: function() {}
    };
})(jQuery); 
