$(document).ready(function(){
	init();
	if(typeof console == 'undefined') {
		console = {
			log: function(msg) { alert(msg); }
		}
	}
})


$(window).resize(function(){
	if($.browser.msie) {
		$('#footer').css('display','none');
		$('#footer').css('display','block');
	}
});

$(window).scroll(function(){
	if($.browser.msie) {
		$('#footer').css('display','none');
		$('#footer').css('display','block');
	}
});

function init(){

	if($('#timeleft:not(:empty)').is('div')) {
		orderTimer();
	}
	
	if($('#login').is('div')) {
		$('form[name=loginform] input:eq(0)').focus();
	}
	
	refreshOrderMenu();
	
	/*$('#login form input').keypress(function (e) {
		if (e.which == 13) {
			$('#login form').submit();
		}
	});*/
	
	$('form input').keypress(function (e) {
		if (e.which == 13) {
			$(this).parents('form').submit();
		}
	});
	
	if($.browser.msie == $.browser.version == '7.0') {
		if($('#specials').width()>800){
			$('#specials').css('width','800px');
		}	
	}
}


function orderTimer(){

	refreshTimer(orderTimeLeft);
	setTimeout(function(){
		orderTimeLeft--;
		refreshTimer();
		
		if(orderTimeLeft>0) {
			orderTimer();
		} else {
			window.location.href=timeoutUrl;
		}		
	},60000);
	
	function refreshTimer(orderTimeLeft){
		var hours = parseInt(orderTimeLeft / 60);
		var mins = orderTimeLeft % 60;
		if(mins<10) {mins='0'+mins}; 
		$('#timeleft span').html(hours + ':' + mins);
	}
}


function refreshOrderMenu(){

	

	// company list
	$('.companymenulist').each(function(i){
		$('.companymenulist:eq('+i+') img.checkbox').click(function(){
			
			if($(this)[0].className.search(/disabled/)==-1) {
				if($(this)[0].className.search(/sel/)==-1) {
	
					$('.companymenulist:eq('+i+') img.sel').each(function(){
						$(this).removeClass('sel');
					})
					$.get("/order/company/additem/"+$(this).attr('id').substring(8, $(this).attr('id').length)+"/", function(data){
						$('.companyBlock').html(data)
					});
					
					$(this).addClass('sel');
				} 
			}
			
		});
	});
	

	// user list
	$('#fullmenulist a.addProduct').click(function(){
		var fowWho;
		if($(this).parents('tr:eq(0)').find('input').val()!='type a name...') {
			forWho = $(this).parents('tr:eq(0)').find('input').val();
		} else {
			forWho = 'For myself';
		}
		$.get("/order/cart/additem/"+$(this).attr('rel')+"/"+forWho+'/', function(data){
			$('.userBlock').html(data)
		});
	});

	// specials table
	$('.spectable a.addProduct').click(function(){
		var fowWho;
		if($(this).parents('tr:eq(0)').find('input').val()!='type a name...') {
			forWho = $(this).parents('tr:eq(0)').find('input').val();
		} else {
			forWho = 'For myself';
		}
		$.get("/order/cart/additem/"+$(this).attr('rel')+"/"+forWho+'/', function(data){
			$('.userBlock').html(data)
		});
	});
	
	// name input focus
	$('.forwho input').click(function(){
		$(this).val('');
	});
	
	// name input unfocus
	$('.forwho input').blur(function(){
		if($(this).val()=='') {
			$(this).val('type a name...');
		}
	})
	
	// plus
	$('.userBlock .btn_plus').live('click',function(){
		$.get($(this).siblings('span').html(),function(data){
			$('.userBlock').html(data)
		});
		
	});
	
	// minus
	$('.userBlock .btn_minus').live('click',function(){
		$.get($(this).siblings('span').html(),function(data){
			$('.userBlock').html(data)

		});
		
	});

	// clear group	
	$('.userBlock .btn_clrgrp').live('click',function(){
		$.get($(this).attr('rel'),function(data){
			$('.userBlock').html(data)
		});
		
	});
	// clear all
	$('.userBlock .btn_clrall').live('click',function(){
		$.get($(this).attr('rel'),function(data){
			$('.userBlock').html(data)
		});
		
	});
	
	
	// TODO javitani az url-t, hogy az usereket hozza be, click esemenyre is megjelenjen a lista
	$('table#fullmenulist tr td.forwho input').autocomplete({
		serviceUrl:'/ajax/groupnames/',
		minChars:1,
		maxHeight:400,
		width: 115,
		deferRequestBy: 0
	});
	
	// TODO javitani az url-t, hogy az usereket hozza be, click esemenyre is megjelenjen a lista
	$('.spectable input').autocomplete({
		serviceUrl:'/ajax/groupnames/',
		minChars:1,
		maxHeight:400,
		width: 115,
		deferRequestBy: 0
	});
	
	
	//chekout form radio gombok
	$('#checkoutform img.checkbox').click(function(){
		$(this).next('input').click();
		$('#checkoutform img.checkbox').removeClass('sel');
		$(this).addClass('sel');
	});
	
	
	//checkout form ido input
	var empty_input = true;
	if($("input[name=be_ready_at]").val()=="type in the time...") {
		empty_input = false;
	}
	$("input[name=be_ready_at]").mask("99:99");
	if(!empty_input) {
		$("input[name=be_ready_at]").val('type in the time...');
	}
	
	$("input[name=be_ready_at]").click(function(){
		$(this).val('__:__');
		setCaretTo($(this)[0],0);
	});
	
	$("input[name=be_ready_at]").blur(function(){
		var iArr = new Array();
		iArr = $(this).val().split(':');
		$(this).siblings('span.error').remove();
		
		if(iArr[0]>24 ||iArr[1]>59 || $(this).val()=='') {
			$(this).parents('p:eq(0)').append('<span class="error">&nbsp;Please enter valid time format (hh:mm).</span>')
			$(this).focus();
			$(this).val('__:__');
	 		setCaretTo($(this)[0],0);
		}
	});
	
	//order formok
	$('a.button:contains(Send your order),a.button:contains(Checkout),a.button:contains(Personal Setups),a.button:contains(Send your order)').click(function(){
		$(this).parents('form').submit();
	});
	
	
	// google map
	if($('#map').is('div')){
	
		
		 var baseIcon = new GIcon(G_DEFAULT_ICON);
	        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	        baseIcon.iconSize = new GSize(20, 34);
	        baseIcon.shadowSize = new GSize(37, 34);
	        baseIcon.iconAnchor = new GPoint(9, 34);
	        baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		   
		var map = new GMap(document.getElementById("map"));
		map.centerAndZoom(new GPoint(-6.243799,53.349247), 4);
		map.addControl(new GSmallMapControl());
		
		function createMarker(point, index) {
			// Create a lettered icon for this point using our icon class
			var letter = String.fromCharCode("A".charCodeAt(0) + index);
			var letteredIcon = new GIcon(baseIcon);
			letteredIcon.image = "http://www.google.com/mapfiles/markerC.png";

			// Set up our GMarkerOptions object
			markerOptions = { icon:letteredIcon };
			var marker = new GMarker(point, markerOptions);

			setTimeout(function(){
				marker.openInfoWindowHtml("<strong>Caffè Parigi</strong><br /><br /><strong>17-19 Sir John Rogerson Quay, Dublin</strong><br />Caffé/Restaurant, private dining, catering, meeting space and online ordering");
			},30);
			return marker;
        	}
        	
        	var bounds = map.getBounds();
	        var southWest = bounds.getSouthWest();
	        var northEast = bounds.getNorthEast();
	        var lngSpan = northEast.lng() - southWest.lng();
	        var latSpan = northEast.lat() - southWest.lat();
		map.addOverlay(createMarker(new GPoint(-6.243799,53.346247), 0));
		
	}
}


function setCaretTo(obj, pos) {
	if(obj.createTextRange) {
		/* Create a TextRange, set the internal pointer to
		   a specified position and show the cursor at this
		   position
		*/
		var range = obj.createTextRange();
		range.move("character", pos);
		range.select();
	} else if(obj.selectionStart) {
		/* Gecko is a little bit shorter on that. Simply
		   focus the element and set the selection to a
		   specified position
		*/
		obj.focus();
		obj.setSelectionRange(pos, pos);
	}
}

