var serviceUrl = "/europark/service.php";

//
//
//

(function() {
	
	var id = 0;
	
	window.getUniqId = function() {
		id = id + 1;
		return 'ep-id-' + id; 
	}
	
})()

//
// Util fn-s
//
String.prototype.template = function (o) { 
    return this.replace(/{([^{}]*)}/g, 
        function (a, b) { 
            var r = o[b]; 
            return typeof r === 'string' || typeof r === 'number' ? r : a; 
        } 
    ); 
};

Date.prototype.toEtDate = function () {
 function pad(n){return n<10 ? '0'+n : n}
 return pad(this.getDate()) + '.'
      + pad(this.getMonth()+1)+'.'
      + this.getFullYear();

}

Date.prototype.toEtTime = function () {
 function pad(n){return n<10 ? '0'+n : n}
 return pad(this.getHours())+':'
      + pad(this.getMinutes());

}

//History
function getHash() {
	var href = top.location.href, i = href.indexOf("#");
	return i >= 0 ? href.substr(i + 1) : '';
}

function getQuery() {
	q = window.location.search
	if(q[0] == '?') q = q.substr(1)
	var params = {}
	var qa = q.split('&');
	for(var p =0; p < qa.length; p++) {
		parm = qa[p].split('=');
		params[parm[0]] = parm[1];
	}
	return params;
}

function handleStateChange(hash) {
	
	var oldHash = $('#ep-history').attr('value');
	var oldParts = oldHash.split(':');
	oldCity  = (!isNaN(oldParts[0]) ? '' : oldParts[0]);
	
	var q_vars = getQuery();
	
	if(hash == '' && oldCity != '') {
		//Default
		selectCity($('#city_id').attr('value') || $('#city_id option:eq(0)').attr('value'));	
	}
	
	
	var parts = hash.split(':');

	if(!isNaN(parts[0])) {
		
		if(oldCity != '') {
			//Default
			selectCity($('#city_id').attr('value') || $('#city_id option:eq(0)').attr('value'));
		}
		
		loadCarParkData(parts[0],(q_vars['step'] && q_vars['step'] == '2'))
		
	} else if(parts[0]) {
		
		if(oldCity != parts[0]) {
			selectCity(parts[0]);
			$("#city_id").attr('value', parts[0]).sb("refresh");
		}
		
		if(parts[1]) {
			loadCarParkData(parts[1],(q_vars['step'] && q_vars['step'] == '2'))
		}
	}
}

//
// Translate
//

var gt = new Gettext({ 'domain' : 'public' });
function _ (msgid) {
	return gt.gettext(msgid);
}

//
// Tabs dropdown
//

function toggleDropdown(drpdwn) {
	//var is_hovered = $(drpdwn).hasClass('hover');
	$(drpdwn).toggleClass('hover');
	
	
	
	/*
	num =  is_hovered ? 1 :  $('a', drpdwn).size();
	$(drpdwn).stop(true, false).animate({ height: num * ($('a', drpdwn).height()+2) },200,
		function() {
			if(is_hovered) {
				$(drpdwn).toggleClass('hover');
			}
		}
	);
	*/
	
}

function searchAddress() {
	searchControl.execute(document.getElementById('map_search').value);
	$('#map_tabs .results').show().toggleClass('selected');
	$('#map_tabs .map').toggleClass('selected');
}

function showZoneInfo(city) {
	$('#zonelist .zonelist').hide();
	$('.city_name_in_zl').text(cities[city]['name']);
	//$('#zonelist_city_'+city).show();
}

function zonelistToggle() {
	if($('#zl_headline_hidden').css('display') != 'none') {
		$('#zonelist_city_'+$('#city_id').attr('value')).fadeIn();
		$('#zl_headline_hidden').hide();
		$('#zl_headline_visible').show()
	} else {
		$('#zonelist .zonelist').hide();
		$('#zl_headline_visible').hide();
		$('#zl_headline_hidden').show()
	}
}

function viewCarpark(zone_id) {
	//window.location.search = '?page=' + zones[zone_id]['id'];
	$.get('./?page=' + zones[zone_id]['id'] , function(data) {
		
		data += '<div class="buttons">' +
					'<button type="button" onclick="hideStep(\'#zone_details\')" class="awesome">&#171; ' + _('Tagasi') + '</button>' +
				'</div>';
		
		
		$('#overlay').show();
		$('#zone_details').html(data).fadeIn();
		
		//
		// Enable gmap
		//
		var maps = $('#zone_details').find('.zone_map');
		if(maps[0]) {
			var latlng = maps.attr('location');
			if(latlng) {
				
				latlng = latlng.split(",");
				var zoomlvl = maps.attr('zoomlevel') || 13;
				var zname = maps.attr('name');
				
				//Setup map
				var map = new GMap2(maps[0]);
				map.setCenter(new GLatLng(latlng[0], latlng[1]), Number(zoomlvl));
			
				//Set marker
				var zImage = new GIcon();
				zImage.image = "europark/img/parking_active.png";
				zImage.shadow = "europark/img/parking_shadow.png";
				zImage.iconSize = new GSize(50, 50);
				zImage.shadowSize = new GSize(70, 50);
				zImage.iconAnchor = new GPoint(25, 50);
				zImage.infoWindowAnchor = new GPoint(10, 10);
				var marker = new GMarker(new GLatLng(latlng[0], latlng[1]), { icon:zImage });
				map.addOverlay(marker);
				
				//Set caption
				if(zname) {
					
				}
			}
		}
		
		$.scrollTo( "#zone_details", 800, {offset:-26} );
	});
}

function viewMPark(mzone) {
	$.get('./?page=mparking-'  + _LANG + '&mparking_code=' + mzone, function(data) {
		
		data += '<div class="buttons">' +
					'<button type="button" onclick="hideStep(\'#zone_details\')" class="awesome">&#171; ' + _('Tagasi') + '</button>' +
				'</div>';
		
		
		$('#overlay').show();
		$('#zone_details').html(data).fadeIn();
		$.scrollTo( "#zone_details", 800, {offset:-26} );
		
	});
}

function showTerms() {
	$.get('./?page=terms-' + _LANG , function(data) {
		
		data += '<div class="buttons">' +
					'<button type="button" onclick="$(\'#terms_div\').fadeOut()" class="awesome">' + _('Close') + '</button>' +
				'</div>';
		
		
		$('#terms_div').html(data).fadeIn();
		//$.scrollTo( "#terms_div", 800, {offset:-26} );
	});
}

function toggleSideRem() {
	if($('#side_login_form').is(':visible')) {
		$('#side_login_form').slideUp(400, function() {
			$('#side_reminder_form').slideDown();
		});
	} else {
		$('#side_reminder_form').slideUp(400, function() {
			$('#side_login_form').slideDown();
		});
	}
	
}

$(document).ready(function() { 
	$('.dropdown').bind('mouseenter', function() {
		toggleDropdown(this);
	});
	
	$('.dropdown .dd_menu').bind('mouseleave', function() {
		toggleDropdown($(this).parent());
	});
	/*
	$('.dropdown a').bind('click', function() {
		var drpdwn = $(this).parents('.dropdown');
		drpdwn.find('a').removeClass('selected');
		$(this).addClass('selected');
		drpdwn.find('.dd_selected').text($(this).text());
		//toggleDropdown();
	});
	*/
	$('#map_search').bind('keyup', function(e) {
		if(e.keyCode == '13') {
			$('#g_page').val('-');
			searchAddress() 
		}
	});
	
	$('#addr_search_btn').bind('click', function(e) {
		$('#g_page').val('-');
		searchAddress() 
	});
	
	$('#map_tabs .map').bind('click', function(e) {
		$(this).toggleClass('selected').siblings().toggleClass('selected');
		$('#search_results').fadeOut();
	});
	
	$('#map_tabs .results').bind('click', function(e) {
		$(this).toggleClass('selected').siblings().toggleClass('selected');
		$('#search_results').fadeIn();
	});
	
	//Bin search box
	//
	
	//
	// Make select nice
	//
	$("#city_id").sb({
	});
	
	//
	// Fix display property for error labels
	//
	var error_labels = [
		"bill_email",
		"client_name",
		"billing_address",
		"billing_index",
		"billing_city",
		"contact_telephone",
		"contact_email",
		"c_password1",
		"c_password2",
		"contact_person",
		"company_name",
		"billing_email",
		"company_reg",
		"cbilling_address",
		"cbilling_index",
		"cbilling_city",
		"ccontact_telephone",
		"ccontact_email",
		"cc_password1",
		"cc_password2",
		"form_login_username",
		"form_login_passwd",
		"form_reminder_email"
	];
	for( var i; i < error_labels.length; i++) {
		$("label[for=" + error_labels[i] + "].error").hide();
	}
	
});

function validateForm(form) {
	var validator = $(form).validate({
		
		rules: {
			form_login_username: { required: true, email: true },
			form_login_passwd: { required: true, rangelength: [5, 32] },
			form_reminder_email: { required: true, email: true }
		},
		ignore: ".ignore"
	});
	
	if(validator.form()) {
		validator['currentForm'].submit();
	}
}

//
// Basket and stuff
//

function getBasket(json){
	
	if(json.error) {
		alert(json.error + ' - ' + json.message);
	}
	
	if (json == null || json.session_id == null){
		return;
	}
	
	if(json.items.length == 0) {
		$("#step_three").hide();
		//$("#step_four").hide();
		//$("#step_five").hide();
		$('#basket tbody tr').remove();
		
		//$('#hidden_basket *').remove();
		//$('#hidden_basket').hide();
		
		return;
	}
	
	//Clear all rows
	$('#basket tbody tr').remove();
	//$('#hidden_basket *').remove();
	//$('#hidden_basket').append('<h2>Sinu ostukorvis</h2><ul></ul><a href="#step_three">Vaata lähemalt/Osta</a>');
	
	/*
	if(json.allow_cards == false) {
		$('#permit_cards, .cards').hide();
	} else {
		$('#permit_cards, .cards').show();
	}
	*/
	
	//Add all rows
	var items = 0;
	$.each(json.items, function(i, val) {
		addBasketRow(val);
		//addHiddenBasketRow(val);
		if(val.item_id == Number(val.item_id)) items++;
	});
	
	$("#totalPrice").text(json.total + " " + json.currency);
	setOddRows();
	/*
	setOddRows('#hidden_basket li');
	if(items > 0) {
		try {
			$('#hidden_basket').show().animate({display: 'block', backgroundColor: '#FFAE0B'}, 1000).animate({backgroundColor: '#FFFFFF'}, 1000);
		} catch (e) {};
		
	} else {
		$('#hidden_basket').fadeOut();
	}
	*/
	
	$("#step_three").show();
	//$("#step_four").show();
	//$("#step_five").show();
}

function setupDatePicker(obj) {
	$(obj).DatePicker({
		format:'d.m.Y',
		date: $(obj).val(),
		current: $(obj).val(),
		starts: 1,
		position: 'r',
		onBeforeShow: function(){
			$(obj).DatePickerSetDate($(obj).val(), true);
		},
		onChange: function(formated, dates){
			$(obj).val(formated);
			$(obj).DatePickerHide();
		}
	});
}

var slider_arr = {};

function cloneForm(me) {
	
}

function loadCarParkData(id, show, tariff_id){
	
	var cross_sell = $("#cross_sell");
	cross_sell.hide();
	cross_sell.html('');
	var cross_sell_prices = {};
	var has_prices = false;
	var can_pay_mobile = false;
	
	$.post(serviceUrl, {action : "getParkingzoneDetails", parkingzone_id : id, language: _LANG }, function(json){
		
		if(json.tariffs && json.tariffs.price && json.tariffs.price.price_id != null) {
			json.tariffs.price = new Array(json.tariffs.price);
		}
		
		//
		// Go through prices to see what payment options we got
		// Also check if the prices has some times assosiated with it
		//
		var payment_opts = {};
		var has_times = false;
		$.each(json.tariffs.price, function(i, val) {	
			if(!val.show_public) return true;
			
			if(val.start_time || val.end_time) {
				has_times = true;
			}
			
			if(val.is_mobile) {
				can_pay_mobile = true;
				payment_opts['pay_mobile'] = [_('Pay with mobile'), _('Possibility to pay by mobile parking. Parking zone: ') + json.parking_code ];
			}
			
			if(val.is_cash) {
				payment_opts['pay_cash'] = [_('Pay with cash'), _('Parkingmeter accepts cash')];
			}
			
			if(val.is_card) {
				payment_opts['pay_card'] = [_('Pay with card'), _('Parkingmeter accepts cards')];
			}
			
			if(val.sell_public) {
				payment_opts['pay_web'] = [_('Pay in web'), _('Can buy permit from the web')];
			}
			
			return true;
		});
		
		//
		// Make HTML
		//
		var html = '<h2>' + json.name + (json.parking_code ? ' (' + json.parking_code + ')': '') + '</h2>';
		html += '<div class="p_content">';
		
		
		
		//html += '<div class="address">' + json.address + '</div>';
		
		if(json.description && json.description.length) {
			html += '<dl><dt>' + _('Parkingarea info') + ':</dt><dd>';
			html += '<div class="info">' + json.description + '</div>';
			html += '<b class="payment_opts_title">' + _('Payment options') + ':</b>';
		} else {
			html += '<dl><dt>' + _('Payment options') + ':</dt><dd>';
		}
		
		if(payment_opts != {}) {
			//html += '<b>' + _('Payment options:') + '</b><hr class="clear" style="margin-bottom: 10px">'
			html += '<div class="payment_options">';
			for(var i in payment_opts) {
				html += '<div qttip_style="margin-top: -7px;" class="' + i + '" title="' + payment_opts[i][1] + '"><!-- --></div>';
			}
			html += '<hr class="clear"></div>';
		}
		
		
		html += '</dd></dl><dl><dt>' + _('Price info') + ':</dt><dd>';
		
		
		html += '<ul class="price_info">';
		
		if(!json.tariffs.price) {
			json.tariffs.price = new Array();
		}
		
		has_prices = false;
		has_crossell = false;
		prices_over_month = new Array();
		prices_incross_sell = {};
		pim = 0;
		var last_times = '';
		
		//Go throgh prices
		$.each(json.tariffs.price, function(i, val) {
			
			if(!val.show_public) return true;
			
			has_prices = true;
			
			//Fix zones array
			if(val.zones.parkingzonelist && val.zones.parkingzonelist.parkingzone_id != null) {
				val.zones.parkingzonelist = new Array(val.zones.parkingzonelist);
			}
			
			//
			// go through prices that are  > 1 month and add them to selection
			//
			var per_parts = /([-+]{0,1})(\d+)\s(DAY|DAYS|WEEK|WEEKS|MONTH|MONTHS|YEAR|YEARS)/i.exec(val.period);
			
			if(val.zones.parkingzonelist && val.zones.parkingzonelist.length == 1 && per_parts && per_parts.length) {
				if(per_parts[3] == 'MONTH' || per_parts[3] == 'MONTHS' || per_parts[3] == 'YEAR' || per_parts[3] == 'YEARS') {
					prices_over_month[prices_over_month.length] = '<input name="tariff_id" ' + (pim == 0 ? ' checked ':'') + ' class="checkbox" type="radio" onchange="changePrices(this, \'' + val.price_id + '\')" id="tariff_id_' + val.price_id + '">' +
						'<span class="price"><b>' + (val.price /100) + ' ' + val.currency + '</b></span> <span class="period">' + _(val.period) + '</span>';
					
					//Add time period if neccisary
					//
					// NB! REFACTOR THIS
					if(has_times) {
						
						//Calculate weekdays
						var wd_str = _('Mon') + '-' + _('Sun');
						if(val.weekdays) {
							var wd_arr = val.weekdays.split("").sort();
							var wd_hash = { "1" : _("Mon"),"2" : _("Tue"),"3" : _("Wed"),"4" : _("Thu"),"5" : _("Fri"),"6" : _("Sat"),"7" : _("Sun") };
							var first_in_range = null;
							var prev_range_obj = null;
							wd_str = '';
							for(var i in wd_arr) {
								
								var d = wd_arr[i];
								if(first_in_range == null) {
									first_in_range = d;
									if(Number(wd_arr[(i-1)]) != (d-1)) {
										wd_str += ',' + wd_hash[d];
									}
								} else if(Number(wd_arr[(i-1)]) == (d-1)) {
									//Continue
								} else {
									if(Number(wd_arr[(i-1)]) != first_in_range) {
										wd_str += '-' + wd_hash[wd_arr[(i-1)]];
									}
									first_in_range = null;
									wd_str += ',' + wd_hash[d];
								}
								
							}
							//Special check for last printout
							if((wd_arr[(wd_arr.length-1)] - 1 ) == Number(wd_arr[(wd_arr.length-2)])) {
								wd_str += '-' + wd_hash[wd_arr[(wd_arr.length-1)]];
							}
							wd_str = wd_str.substr(1);
						}
						
						prices_over_month[prices_over_month.length-1] += ' <span class="times">(' + wd_str + ' ' + (val.start_time ? val.start_time.substr(0,5) : '00:00' ) + ' - ' + (val.end_time ? val.end_time.substr(0,5) : '24:00' ) + ')</span>';
				
						
						
						//END REFACTOR THIS
					}
					
					pim++;
				}
			} else if(val.zones.parkingzonelist && val.zones.parkingzonelist.length > 1 && per_parts && per_parts.length) {
				
				var st_html = 'Soovin osta ';
				$.each(val.zones.parkingzonelist, function(i2, val2) {
					if(i2 > 0) {
						st_html += ' ja ';
					}
					st_html += '<b>' + val2.name + '</b>';
				});
				st_html += ' parkimisluba ainult: ';
				
				
				
				
				var cross_sell_html = '<input name="tariff_id" class="checkbox" type="radio" onchange="changePrices(this, \'' + val.price_id + '\')" id="cross_sell_' + val.price_id + '"><label for="cross_sell_' + val.price_id + '">';
				cross_sell_html += '<span class="price"><b>' + (val.price /100) + ' ' + val.currency + '</b></span> <span class="period">' + _(val.period) + '</span> !';
				cross_sell_html += '</label>';
				
				if(!prices_incross_sell[st_html]) {
					prices_incross_sell[st_html] = [cross_sell_html]
				} else {
					prices_incross_sell[st_html].push(cross_sell_html);
				}
				
			}
			
			//
			// Add cross-sell prices
			//
			if(val.zones.parkingzonelist && val.zones.parkingzonelist.length > 1 && !has_crossell) {
				
				cross_sell_prices[val.price_id] = val.price_id;
				
				//Add prices part
				html += '<li class="header">' + 'Ostes ';
				
				var cross_sell_html = '<input name="tariff_id" type="radio" class="checkbox" onchange="changePrices(this, \'' + val.price_id + '\')" id="cross_sell_' + val.price_id + '"><label for="cross_sell_' + val.price_id + '">Soovin osta ';
				$.each(val.zones.parkingzonelist, function(i2, val2) {
					if(i2 > 0) {
						html += ' ja ';
						cross_sell_html += ' ja ';
					}
					html += '<b>' + val2.name + '</b>';
					cross_sell_html += '<b>' + val2.name + '</b>';
				});
				
				html += ' parkimisluba</li>';
				cross_sell_html += ' parkimisluba';
				cross_sell_html += ' ainult: <span class="price"><b>' + (val.price /100) + ' ' + val.currency + '</b></span> <span class="period">' + _(val.period) + '</span> !';
				cross_sell_html += '</label>';
				//Add cross sell part
				
				
				//cross_sell.html(cross_sell_html);
				//cross_sell.show();
				has_crossell = true;
				
			}
			
			//
			// Display times if needed
			//
			if(has_times) {
				
				//Calculate weekdays
				var wd_str = _('Mon') + '-' + _('Sun');
				if(val.weekdays) {
					var wd_arr = val.weekdays.split("").sort();
					var wd_hash = { "1" : _("Mon"),"2" : _("Tue"),"3" : _("Wed"),"4" : _("Thu"),"5" : _("Fri"),"6" : _("Sat"),"7" : _("Sun") };
					var first_in_range = null;
					var prev_range_obj = null;
					wd_str = '';
					for(var i in wd_arr) {
						
						var d = wd_arr[i];
						if(first_in_range == null) {
							first_in_range = d;
							if(Number(wd_arr[(i-1)]) != (d-1)) {
								wd_str += ',' + wd_hash[d];
							}
						} else if(Number(wd_arr[(i-1)]) == (d-1)) {
							//Continue
						} else {
							if(Number(wd_arr[(i-1)]) != first_in_range) {
								wd_str += '-' + wd_hash[wd_arr[(i-1)]];
							}
							first_in_range = null;
							wd_str += ',' + wd_hash[d];
						}
						
					}
					//Special check for last printout
					if((wd_arr[(wd_arr.length-1)] - 1 ) == Number(wd_arr[(wd_arr.length-2)])) {
						wd_str += '-' + wd_hash[wd_arr[(wd_arr.length-1)]];
					}
					wd_str = wd_str.substr(1);
				}
				
				
				var new_times = '';
				new_times = wd_str + ' ' + (val.start_time ? val.start_time.substr(0,5) : '00:00' ) + ' - ' + (val.end_time ? val.end_time.substr(0,5) : '24:00' );
				
				if((new_times != last_times) && (val.start_time && val.end_time)) {
					last_times = new_times;
					
					html += '<li class="time_display">' + last_times + '</li>';
				}
				
				//console.log('Prices', json.tariffs.price)
			}
			
			//
			// Payment options as qtip
			//
			var qtip_html = '';
			if(val.is_mobile) {
				can_pay_mobile = true;
				qtip_html += '<li class=\'pay_mobile\'>' + _('Possibility to pay by mobile parking. Parking zone: ') + json.parking_code + '</li>';
			}
			
			if(val.is_cash) {
				qtip_html += '<li class=\'pay_cash\'>' + _('Parkingmeter accepts cash') + '</li>';
			}
			
			if(val.is_card) {
				qtip_html += '<li class=\'pay_card\'>' + _('Parkingmeter accepts cards') + '</li>';
			}
			
			if(val.sell_public) {
				qtip_html += '<li class=\'pay_web\'>' + _('Can buy permit from the web') + '</li>';
			}
			
			
			if(qtip_html.length) {
				qtip_html = 'title="<ul class=\'payment_opts_list\'>' + qtip_html + '</ul>"';
			}
			
			//
			// Add mian price display
			//
			html += '<li><span class="period">' + _(val.period) + '</span> <span class="price" ' + (qtip_html.length ? qtip_html : '') + '>' + (val.price /100) + ' ' + val.currency + '</span>';
			
			if(val.sell_public) {
				html += '<a href="javascript:" onclick="buyCarpark(\'' + json.parkingzone_id + '\',\'' + val.price_id + '\')" class="pay_web awesome orange" title="' + _('Click to buy') + '">' + _('Buy') + ' »</a>';
			}
			
			//Add buy button if sellable
			
			
			html += '</li>';
			
			//Add info on next row
			if(val.info && val.info.length) {
				html += '<li class="info">' + val.info + '</li>';
			}
			
			return true;
			
		});
		
		
		//DO cross sell html
		var c_price_html = '';
		for (var p in prices_incross_sell) {
			
			c_price_html += '<span class="header">' + p + '</span><ul>';
			
			for(i=0;i<prices_incross_sell[p].length;i++) {
				c_price_html += '<li>' + prices_incross_sell[p][i] + '</li>';
			}
			c_price_html += '</ul>';
			
		}
		if(c_price_html.length) {
			
			cross_sell.html(c_price_html);
			cross_sell.show();
		}
		
		//Do price list
		if(prices_over_month.length) {
			var price_html = '<ul>';
			for(i=0;i<prices_over_month.length;i++) {
				price_html += '<li>' + prices_over_month[i] + '</li>';
			}
			price_html += '</ul>';
			$('#price_list').html(price_html);
		}
		
		//Do main HTML
		if(!has_prices) {
			html += '<li>Müügil ainult parkimspiletid</li>';
		} else {
			getPurchaseDetails(id);
		}
		
		html += '</ul>';
		
		html += '</dd></dl><hr class="clear">';
		
		//
		// Add links
		//
		html += '<div class="p_links">';
		if(json.parking_code && can_pay_mobile) {
			html += '<a href="javascript:" onclick="viewMPark(\'' + json.parking_code + '\')" class="view">' + _('How to pay with mobile') + '</a>';
		}
		if(1) {
			html += '<a href="javascript:" onclick="viewCarpark(\'' + json.parkingzone_id + '\')" class="view">' + _('View more') +'</a>';
		}
		if(prices_over_month.length) {
			html += '<button type="button" onclick="buyCarpark(\'' + json.parkingzone_id + '\')" class="awesome orange">' + _('Buy a permit') + ' &#187;</button>';
		}
		html += '<hr class="clear"></div>';
		html += '<hr class="clear"></div>';
		
		$("#parkinfo").html(html);
		
		//
		// Enable qtips
		//
		$('.pay_mobile, .pay_cash, .pay_card, .pay_web, .price').qtip({
			style: {
				name: 'cream',
				width: 'auto',
				tip: 'topMiddle',
				padding: 0 /* ,
				border: {
					width: 1,
					radius: 0
				}
						   */
			},
			position: {
				corner: {
				   target: 'bottomMiddle',
				   tooltip: 'topMiddle'
				}
			}
		});

		
		//
		// Slide down stuff
		//
		if(!$("#parkinfo").is(':visible')) {
			$("#parkinfo").slideDown('fast');
		}
		
		//Show only basked if we can by
		/*
		if(!has_prices) {
			$("#step_two").hide();
		} else {
			//$("#step_two").show();
			$("#step_two").hide();
		}
		*/
		$("#purchase_interrupted").hide();
		if(show) {
			$.scrollTo( "#step_two", 800, {offset:-26} );
		} else {
			$("#step_two").hide();
		}
		
		//
		// Change map 
		//
		for(m in allMarkers) {
			if(id == allMarkers[m].value) {
				allMarkers[m].setImage("europark/img/parking_active.png");
				lastMarker = allMarkers[m];
				emap.panTo(allMarkers[m].getLatLng());
				
			} else {
				allMarkers[m].setImage("europark/img/parking.png");
			}
		}
		
		//
		// Set predefined tariffs
		//
		if(tariff_id > 0) {
			$('input[name=tariff_id]').attr('checked', false);
			$('#tariff_id_' + tariff_id).attr('checked', true);
		}
		
		
	}, "json");
	
	//.animate({display: 'block', backgroundColor: '#FFAE0B'}, 1000).animate({backgroundColor: '#FFFFFF'}, 1000);

}

function buyCarpark(id, tariff_id) {
	$("#overlay").show();
	$("#step_two").css('z-index','9000003').fadeIn('slow');
	$.scrollTo( "#step_two", 800, {offset:-26} );
	
	//Select right tariff
	if(tariff_id > 0) {
		$('input[name=tariff_id]').attr('checked', false);
		$('#tariff_id_' + tariff_id).attr('checked', true);
	}
	
}

function hideStep(step) {
	$(step).fadeOut('slow', function() {
		if(step == '#step_three') {
			if($("#step_two").css('display') == 'block') {
				$.scrollTo( '#step_two', 800, {offset:-26} );
				$("#step_two").css('z-index','9000003');
			} else {
				$("#step_two").hide();
				$("#overlay").hide();
				$.scrollTo( 0, 800 );
			}
		} else if(step == '#zone_details') {
			$.scrollTo( '#step_one', 800, {offset:-26} );
			$("#overlay").hide();
		} else {
			$("#overlay").hide();
			$.scrollTo( 0, 800 );
		}
	});
}

function getPurchaseDetails(id) {
	
	var num_permits = $('#num_permits').attr('value') || 1;
	var cross_sell_prices = {};

	$.post(serviceUrl, {action : "getPurchaseFields", parkingzone_id : id}, function(json){
		
		$("#parkingzone_id").attr('value', id);
		
		var has_dates = new Array();
		var has_datetimes = {};
		var has_periods = new Array();
		var ret = '';
		var q_vars = getQuery();
		
		//
		// Make fixed period form
		//
		
		for(var n = 0; n < num_permits; n++) {
			
			ret += '<tbody>';
		
			$.each(json.fields, function(i, val) {
				
				if(!val.display) return true;

				var classes = new Array();
				
				var fld_cls = '';
				if(val.is_required) {
					classes.push('required');
					fld_cls += ' required ';
				}
				
				var cls = '';
				/*
				if(val.id == 7 || val.id == 3) {
					classes.push('not_free');
				} 
				*/
				
				//Check default value
				if(q_vars["field_" + val.id]) {
					val.default_value = q_vars["field_" + val.id];
				}
				
				var s_id = getUniqId();
				
				ret += '<tr>';
				ret += "<td style=\"clear:left\" class=\"" + classes.join(' ') + " name\"><label for=\"" + s_id + "\">" + _(val.name) + "</label></td>";
				ret += '<td class="' + classes.join(' ') + ' content">';
				
				switch(val.type){
					case 'DATE':
						//has_dates.push('#field_' + val.id);
					case 'DATETIME':
						//Find date and time part
						var d_val = new Date(strtotime(val.default_value) * 1000);
						
						var the_date = '';
						var the_time = '';
						if(d_val) {
							the_date = d_val.toEtDate();
							the_time = d_val.toEtTime();
						}
						
						//has_datetimes['datetime_field_' + val.id ] =  { weeksBefore: 0, weeksAfter: 53, isPopup: false, locale:DATE_LOCALE_ET, startField: 'field_date_' + val.id, onChange: function() { changeEnd('3') } };
						
						/*
						has_dates['datetime_field_' + val.id ] = { format: 'd.m.Y', flat: false, date: the_date, onChange: function(formated, dates){
							$('datetime_field_' + val.id).val(formated);
							$('datetime_field_' + val.id).DatePickerHide();
							//$("#complaintForm").validate();
						}};
						*/
						has_dates.push({ id: s_id , options: {
							format:'d.m.Y',
							date: d_val,
							enable_from: new Date(strtotime("-1 DAY") * 1000),
							enable_to: new Date(strtotime("+1 MONTH +1 YEAR") * 1000),
							current: the_date,
							starts: 1,
							position: 'r',
							onBeforeShow: function(){
								$(s_id).DatePickerSetDate($(s_id).val(), true);
							},
							onChange: function(formated, dates){
								//Start date
								$('#' + s_id).val(formated);
								
								//End date
								var cb = $('input[field_type=6]:eq(0)');
								
								changePayType(cb[0], cb.parents('td').find('div.dateselect_field').attr('id')) 
								
								
								$('#' + s_id).DatePickerHide();
							},
							onRender: function(date){
								var disabled = false;
								if(this.enable_from || this.enable_to) {
									disabled = true;
									if(this.enable_from) {
										disabled = ( date.getTime() <= this.enable_from.getTime() );
									}
									if(this.enable_to && disabled == false) {
										disabled = ( date.getTime() >= this.enable_to.getTime() );
									}
								}
								
								return { disabled: disabled };
							}
						}});
						
						//
						// Special case for end date
						//
						var hidden = false;
						var date_val = the_date;
						if(val.id == 7) {
							date_val = '';
							hidden = true;
						}
						
						
						//
						// Date field
						//
						ret += '<div id="datetime_field_' + s_id + '" class="datetime_fields" style="' + (hidden ? 'display:none':'') + '">';
						ret += "<input class=\"date_field" + fld_cls + "\" type=\"text\" field_type=\"" + val.id + "\" name=\"field_date_" + val.id + "\" id=\"" + s_id + "\" value=\"" + date_val + "\">";
						ret += '<span class="time_display"><label>' + _('at time') + ': </label>' + the_time + '</span>'
						//ret += "<input class=\"time_field" + fld_cls + "\" readonly type=\"text\" name=\"field_time_" + val.id + "\" id=\"field_time_" + val.id + "\" value=\"" + the_time + "\">";
						ret += '</div>';
						
												
						//
						// Special case for end date
						//
						if(val.id == 7) {
							var v_type_id = getUniqId();
							ret += '<input type="hidden" name="field_6" value="free">';
							//ret += '<span class="is_fixed checkbox"><input type="checkbox" id="' + v_type_id + '" field_type="6" name="field_6" onclick="changePayType(this,\'datetime_field_' + s_id + '\')" checked value="free" /> <label for="' + v_type_id + '">' + _('indefinitely') + '</label></span>';
							//ret += '<span class="time_display">' + the_time + '</span>'
						}
						
						ret += '<label for="' + s_id + '" class="error">' + _('Please fill in ' + val.name ) + '</label>'
						
						break;
					case 'DATESELECT':
						var d_val = new Date(strtotime(val.default_value) * 1000);
						
						var the_date = '';
						var the_time = '';
						if(d_val) {
							the_date = d_val.toEtDate();
							the_time = d_val.toEtTime();
						}
						
						//
						// Date field
						//
						ret += '<div id="datetime_field_' + s_id + '" class="dateselect_field' + fld_cls + '" style="display:none">';
						ret += "<select class=\"dateselect_field" + fld_cls + "\" field_type=\"" + val.id + "\" name=\"field_date_" + val.id + "\" id=\"dateselect_" + s_id + "\" value=\"\">";
						
						if(val.options != null) {
							
							if(val.options.option != null) {
								val.options = val.options.option;
							}
							$.each(val.options, function(io, op) {
								ret += "<option value=\"\" period=\"" + op.value + "\"";
								if (val.default_value == op.value)
									ret += ' selected';
								ret += '>';
								ret += op.name + "</option>";
							});
						}
						ret += "</select>";
						ret += '<span class="time_display"><label>' + _('at time') + ': </label>' + the_time + '</span>'
						//ret += "<input class=\"time_field" + fld_cls + "\" readonly type=\"text\" name=\"field_time_" + val.id + "\" id=\"field_time_" + val.id + "\" value=\"" + the_time + "\">";
						ret += '</div>';
						
						var v_type_id = getUniqId();
						ret += '<input type="hidden" name="field_6" value="free">' + _('indefinitely');
						//ret += '<span class="is_fixed checkbox"><input type="checkbox" id="' + v_type_id + '" field_type="6" name="field_6" onclick="changePayType(this,\'datetime_field_' + s_id + '\')" checked value="free" /> <label for="' + v_type_id + '">' + _('indefinitely') + '</label></span>';
						
						break;
					case 'TEXT':
						ret += "<input class=\"text_field" + fld_cls + "\" type=\"text\" name=\"field_" + val.id + "\" id=\"" + s_id + "\" field_type=\"" + val.id + "\" value=\"" + val.default_value + "\">";
						ret += '<label for="' + s_id + '" class="error">' + _('Please fill in ' + val.name ) + '</label>'
						break;
					case 'TEXTAREA':
						ret += "<textarea class=\"area_field" + fld_cls + "\" rows=\"4\" name=\"field_" + val.id + "\" id=\"" + s_id + "\" field_type=\"" + val.id + "\">" + val.default_value + "</textarea>";
						break;
					case 'SELECT':
						ret += "<select id=\"" + s_id + "\" field_type=\"" + val.id + "\" name=\"field_" + val.id + "\" class=\"select_field" + fld_cls + "\">";
						
						
						
						if(val.options != null) {
							
							if(val.options.option != null) {
								val.options = val.options.option;
							}
							
							$.each(val.options, function(io, op) {
								ret += "<option value=\"" + op.value + "\"";
								if (val.default_value == op.value)
									ret += ' selected';
								ret += '>';
								ret += op.name + "</option>";
							});
						}
					
						ret += '</select>';
						break;
					case 'CHECKBOX':
						ret += "<input class=\"checkbox_field checkbox" + fld_cls + "\" id=\"" + s_id + "\" type=\"checkbox\" field_type=\"" + val.id + "\" name=\"field_" + val.id + "\" value=\"" + val.default_value + "\"";
						if (val.default_value)
							ret += ' checked';
						ret += ">";
						break;
					case 'RADIOBOX':
						ret += '<div>';
						$.each(val.options.option, function(io, op) {
							ret += "<div><input class=\"radio_field checkbox" + fld_cls + "\" id=\"" + s_id + "\" type=\"radio\" field_type=\"" + val.id + "\" name=\"field_" + val.id + "\" value=\"" + val.default_value + "\"";
							if (valdefault_value === op.value)
								ret += ' checked';
							ret += "> " + op.name + "</div>";
						});
						ret  += '</div>';
						break;
					case 'PERIOD':
						ret += '<ul class="period_field">';
						
						if(val.options != null) {
							
							if(val.options.option && val.options.option.id != null) {
								val.options.option = new Array(val.options.option);
							}
							
							$.each(val.options.option, function(io, op) {
								
								var display = '';
								if(cross_sell_prices[op.id]) {
									display = ' style="display:none" ';
								}
								
								ret += '<li' + display + '>';
								
								ret += '<select class="period_select' + fld_cls + '" onchange="changeEnd(' + val.id + ')" ' + (cross_sell_prices[op.id]?' cross_sell="' + op.id + '" ':'') + ' period="' + op.name + '" name="field_period_' + val.id + '_' + op.id + '" id="field_period_' + val.id + '_' + op.id + '">';
								
									var max = 12;
									var def = 0;
									if(/.*minute.*/i.test(op.name)) {
										max = 60;
									} else if(/.*hour.*/i.test(op.name)) {
										max = 24;
									} else if(/.*day.*/i.test(op.name)) {
										max = 31;
									} else if(/.*week.*/i.test(op.name)) {
										max = 5;
									} else if(/.*month.*/i.test(op.name)) {
										max = 12;
									} else if(/.*year.*/i.test(op.name)) {
										max = 2;
									}
									
									if(io == 0) def = 1;
								
								
									for(var i = 0; i <= max; i++) {
										ret += '<option value="' + i + '"'
										+ (i==def ? ' selected ':'') + '>'
										+ i + '</option>';
									}
								ret += '</select>';
								
								ret += '<label>';
								ret += _(op.name) + "</label>";
								
								ret += '</li>';
							});
						}
						
						ret += '</ul>';
						ret += '<span class="period_end" name="field_period_end_' + val.id + '" id="field_period_end_' + val.id + '"></span>';
						break;
					case 'PERIOD_OLD':
						ret += '<div class="period_dates">';
						
						//Fix default value display
						var d_val = new Date(strtotime(val.default_value) * 1000);
	
						if(d_val) {
							d_val = d_val.toEtDate();
						}
						
						//
						// Set start date
						//
						var s_id = '#field_start_date_' + val.id;
						var e_id = '#field_end_date_' + val.id;
						has_dates.push({ id: s_id, options: {
							format:'d.m.Y H:M',
							date: d_val,
							enable_from: new Date(strtotime("+1 DAY -1 SECOND") * 1000),
							enable_to: new Date(strtotime("+1 DAY +1 MONTH +1 YEAR") * 1000),
							current: d_val,
							starts: 1,
							position: 'r',
							onBeforeShow: function(){
								$(s_id).DatePickerSetDate($(s_id).val(), true);
							},
							onChange: function(formated, dates){
								//Start date
								$(s_id).val(formated);
								
								//End date
								
								
								$(s_id).DatePickerHide();
							},
							onRender: function(date){
								var disabled = false;
								if(this.enable_from || this.enable_to) {
									disabled = true;
									if(this.enable_from) {
										disabled = ( date.getTime() <= this.enable_from.getTime() );
									}
									if(this.enable_to && disabled == false) {
										disabled = ( date.getTime() >= this.enable_to.getTime() );
									}
								}
								
								return { disabled: disabled };
							}
						}});
						ret += "<input type=\"text\" name=\"field_" + val.id  + '[0]' + "\" id=\"field_start_date_" + val.id + "\" value=\"" + d_val + "\" class=\"date_field\">";
						
						ret += "<label for=\"" + '#field_end_date_' + val.id +"\" class=\"\"> to </label>";
						
						//
						// Set end date
						//
						
						
						if(val.options.option != null) {
							val.options = val.options.option;
						}
						
						//Find default period
						var e_val = null;
						if(d_val) {
							e_val = new Date(strtotime("+1 MONTH", strtotime(d_val)) * 1000).toEtDate();
						}
						
						/*
						has_dates.push({ id: e_id, options: {
							format:'d.m.Y',
							date: e_val,
							enable_from: new Date(strtotime("+1 DAY -1 SECOND") * 1000),
							enable_to: new Date(strtotime("+1 DAY +1 MONTH +1 YEAR") * 1000),
							current: e_val,
							starts: 1,
							position: 'r',
							onBeforeShow: function(){
								$(e_id).DatePickerSetDate($(s_id).val(), true);
							},
							onChange: function(formated, dates){
								$(e_id).val(formated);
								$(e_id).DatePickerHide();
							},
							onRender: function(date){
								var disabled = false;
								if(this.enable_from || this.enable_to) {
									disabled = true;
									if(this.enable_from) {
										disabled = ( date.getTime() <= this.enable_from.getTime() );
									}
									if(this.enable_to && disabled == false) {
										disabled = ( date.getTime() >= this.enable_to.getTime() );
									}
								}
								
								return { disabled: disabled };
							}
						}});
						
						*/
						
						ret += "<input type=\"text\" readOnly name=\"field_end_date_" + val.id + "\" id=\"field_end_date_" + val.id + "\" value=\"" + e_val + "\" class=\"date_field\">";
	
						//Period silder
						slider_arr[s_id] = new Array();
						
						$.each(val.options, function(io, op) {
							
												
							slider_arr[s_id][slider_arr[s_id].length] = '#field_date_silder_' + op.value;
						
							ret += "<div id=\"field_date_silder_" + op.value + "\" class=\"date_slider\"><span class=\"label\">" + op.name.replace(/(\d|\s)/,'') + "</span></div>";
							has_periods.push({
								id: '#field_date_silder_' + op.value,
								name: 'field_' + val.id + '[' + op.value + ']',
								start: s_id,
								end: e_id,
								text: op.name.replace(/(\d|\s)/,''),
								handler: function(e, ui) {
									
									//Kill other sliders
									for(k in slider_arr[s_id]) {
										if(('#' + e.target.id) != slider_arr[s_id][k]) {
										$(slider_arr[s_id][k]).slider('value', 0);
										}
									}
									
									var new_val = $(s_id).attr('value')
									
									if(new_val) {
										new_val = new Date(strtotime(ui.value + " " + op.name.replace(/(\d|\s)/,''),strtotime(new_val)) * 1000).toEtDate();
										$(e_id).attr('value', new_val);
									}
		
								}
							});
						
						});
	
						ret  += '</div><hr style="height: 1px" class="clear">';
						break;
				}
				
				if(val.message && val.message.length) {
					ret  += '<span class="message">';
					ret  += '<span class="alien"></span>';
					ret  += '<span class="text">' + val.message + '</span>';
					ret  += '</span>';
				}
				
				
				ret += '</td>';
				ret += '</tr>';
			});
			
			ret += '</tbody>';
			
			$("#purchaseDetails").html('<table border="0" cellpadding="0" cellspacing="0">' + ret + '</table>');
			
			//Init dates
			if(has_dates.length > 0) {
				//setupDatePicker(has_dates.join(", "));
				
				for(d in has_dates) {
					$('#' + has_dates[d].id).DatePicker(has_dates[d].options);
				}
			}
			
			if(has_datetimes) {
				for(dt in has_datetimes) {
					
					has_datetimes[dt].startField = $('#' + has_datetimes[dt].startField).eq(0);
					
					$("#" + dt).continuousCalendar(has_datetimes[dt]);
				}
				
				//changeEnd('3');
			}
			
			////$("#singleDate3").continuousCalendar({weeksBefore: 60,weeksAfter: 1, isPopup: true, locale:DATE_LOCALE_ET});
			
			if(has_periods.length > 0) {
				for(d in has_periods) {
					$(has_periods[d].id).dateToUISlider({
						max: 12,
						name: has_periods[d].name,
						value: 0,
						handleText: has_periods[d].text,
						handler: has_periods[d].handler
					});
				}
			}
			
		} //for
		
		$('select.dateselect_field').sb({});
		
		//Mask veh reg input
		var change_case = function() {
            var $this = $(this);
			var val = String($this.val()).toUpperCase();
			val = val.replace(/[^A-Z0-9]/,'');
            $this.val(val);
			
			if (this.setSelectionRange) {
				var len = $this.val().length * 2;
				this.setSelectionRange(len, len);
			}
			$this.val($this.val());	
			
        }
		$("input[name=field_1]").keydown(change_case).keyup(change_case);
		
		//Show right form
		//var form_type = $('#field_6').attr('value');
		//changeForm(form_type);
		
	}, "json");

}

function changePayType(obj, target_id) {
	
	if(obj.checked) {
		$('#' + target_id).slideUp();
		obj.value = 'free';
	} else {
		$('#' + target_id).slideDown();
		obj.value = 'fixed';
		
		if(1) {
			
			//
			// Fill in date values fields
			//
			//ret += '<div id="datetime_field_' + s_id + '" class="dateselect_field" style="display:none">';
			//ret += "<select class=\"dateselect_field" + fld_cls + "\" field_type=\"" + val.id + "\" name=\"field_date_" + val.id + "\" id=\"dateselect_" + s_id + "\" value=\"\">";
			
			var start_date = strtotime($('input[field_type=2]:eq(0)').attr('value'));
			
			$('#' + target_id + ' select.dateselect_field option').each(function(i) {
				var o = $(this);
				var new_date = new Date(strtotime(o.attr('period') + ' -1 DAY',start_date) * 1000 ).toEtDate();
				o.text(new_date).attr('value', new_date);
			});
				
			$('select.dateselect_field').sb("refresh");
			
			//var e_val = new Date(strtotime('+1 MONTH -1 DAY',strtotime($('input[field_type=2]:eq(0)').attr('value'))) * 1000);
			/*
						var the_date = '';
			var the_time = '';
			if(e_val) {
				the_date = e_val.toEtDate();
				the_time = e_val.toEtTime();
				$('#' + target_id + ' input.date_field').attr('value', the_date)
			}
			*/
			
			
		}
		
	}
}

function changePrices(obj, price_id) {
	var sels = $('select[id^=field_period_3_]');
	sels.attr('value', 0).parent().hide();
	if(obj.checked) {
		$('#field_period_3_' + price_id).attr('value', 1).parent().show();
	} else {
		sels.each(function(k,v) {
			var t = $(this);
			if(!t.attr('cross_sell')) {
				if(k == 0) t.attr('value', 1);
				t.parent().show();
			}
		}); 
	}
	
	//
	changeEnd('3');
}

function getCarParkDetail(carParkId){
	$.get('europark/getParkDetails.php', function(){
		myCallBack(param1, param2);
	});
}

function gotoStepThree() {
	//var data = $("#step_two_form").serializeArray();
	
	//
	// Validate form
	//
	var validator = $("#step_two_form").validate({});
	if(!validator.form()) {
		return false;
	}
	
	//
	// Add to basket
	//
	var num_permits = $('#num_permits').attr('value');
	var parkingzone_id = $('#parkingzone_id').attr('value');
	
	var data = {
		action: "addToBasket",
		num_permits: num_permits,
		parkingzone_id: parkingzone_id
	};
	
	var coupon_code = null;
	coupon_code = $('#field_12').val();
	
	//
	// Add purchase details
	//
	$('#purchaseDetails table tbody').each(function(i) {
		$(this).find('input, select').each(function(j) {
			var el = $(this);
			var type = el.attr('field_type');
			data['permits[' + i + '][' + type + '][name]'] = el.attr('name');
			data['permits[' + i + '][' + type + '][type]'] = el.attr('field_type');
			data['permits[' + i + '][' + type + '][value]'] = el.attr('value');
		});
		
		//
		// Add pricetype
		//
		data['permits[' + i + '][11][name]'] = 'field_11';
		data['permits[' + i + '][11][type]'] = '11';
		data['permits[' + i + '][11][value]'] = String($('input[name=tariff_id]:checked')[0].id).replace(/\D+/,'');
		
		//
		// Add coupon
		//
		data['permits[' + i + '][12][name]'] = 'field_12';
		data['permits[' + i + '][12][type]'] = '12';
		data['permits[' + i + '][12][value]'] = coupon_code;
		

	});
	
	$.post(serviceUrl, data, function(json){
		
		//Check for errors
		if(json.error) {
			
			alert("Error\n" + json.message);
			
			return false;
		}
		
		getBasket(json);
			$("#overlay").show();

		$("#step_two").css('z-index','100');
		$("#step_three").css('z-index','9000003').fadeIn('slow');
		$.scrollTo( "#step_three", 800, {offset:-26} );
		
	}, "json");
	
}

function addToBasket(elem){
	var data = $("#step_two_form").serializeArray();
	data[data.length] = { name: "id", value: elem.id};
	data[data.length] = { name: "action", value: "addToBasket"};
	//("#step_three")
	$.post(serviceUrl, data, function(json){
		
		//Check for errors
		if(json.error) {
			
			alert("Error\n" + json.message);
			
			return false;
		}
		
		getBasket(json);
		
	}, "json");

}

function addBasketRow(item){
	var row = "<tr id=\"basket_" + item.item_id + "\"";
	row = row + "><td><span style=\"max-width: 245px; overflow: hidden; display: block\">" + item.description + "</span></td>";
	row = row + "<td>" + item.valid_from + ' - ' + item.valid_to + "</td>";
	row = row + "<td>" + item.sum + ' ' + item.currency + (item.valid_to == '...' ? ' / ' + _(item.price_period):'') + "</td>";
	row = row + "<td class=\"right\"><a href=\"javascript:\" onclick=\"removeFromBasket('" 
		+ "basket_" + item.item_id + "')\" class=\"delete\">" + _('Delete') + "</a></td>";
	row = row + "</tr>";
	$("#basket tbody").append(row);
}


function addHiddenBasketRow(item){
	
	var row = '<li>' + item.description + ': ' + item.valid_from + ' - ' + item.valid_to + '</li>'
	
	$("#hidden_basket ul").append(row);
}

function removeFromBasket(a){
	var id = a.replace("basket_", "");
	$.post(serviceUrl, {action: "removeItemFromQuote", item_id: id}, function(json){
		getBasket(json);
		
	}, "json");
}

function emptyBasket() {
	$.post(serviceUrl, {action: "removeAllItemsFromQuote"}, function(json){
		if(json) {
			return true;
		} else {
			return false;
		}
	}, "json");
}

function setOddRows(par){
	var odd = false;
	if(!par) par = "#step_three tbody tr";
	$(par).each(function(){
		if (odd)
			$(this).removeClass("odd");
		else
			$(this).addClass("odd");
		odd = !odd;
	});
}

function getPointsRequest(){
	var retval;
	$.post(serviceUrl, {action: "getParkingzones"}, getPoints, "json");
	return retval;
}

function getPoints(json){
	var zones;
	if (json.parkingzonelist) {
		zones = json.parkingzonelist;
	} else {
		zones = ['message', json.message];
	}
	showCarParks(zones);
}

function enableBankLinks(me) {
	
	
	
	if(me.checked) {
		
		$('#step_three form button').removeAttr('disabled');
		$('#paymentmethod_1').slideDown();
	} else {
		$('#step_three form button').attr('disabled', 'true');
		$('#paymentmethod_1').slideUp();
	}
}


function enableOrder(me) {
	
	if(me.checked) {
		
		$('#order_div').fadeIn('slow');
	} else {
		$('#order_div').hide();
	}
}

function makeOrder() {
	
	function sendOrder () {

		$.post(serviceUrl, {action: "makeOrder", confirm_email: $('#bill_email').attr('value') }, function(json){
			
			$('#order_div button').attr('disabled', 'true').hide();
			
			if(json.result == 'OK') {
				window.location.replace('?page=tellimuse-kinnitus');
			} else {
				alert('Oops tellimusel tekkis viga! ' + json.message);
			}
			
		}, "json");

	} // fn
	
	//Save contact details if needed
	var new_individual_form = $('#new_individual_form');
	var new_company_form = $('#new_company_form');
	var form_type = '';
	
	$('input[name=client_select]').each(function(id, val) {
		if(val.checked) {
			form_type = val.value;
		}
	});
	
	if(new_individual_form.length || new_company_form.length) {
		
		//
		// Check required fields
		//
		if($.validationEngine.submitValidation($("#new_individual_form"),{
			validationEventTriggers:"keyup blur"
		})) return false;
		
		//
		// Send register
		//
		
		var queryString = (form_type == 'COMPANY' ? new_company_form.formSerialize() : new_individual_form.formSerialize() );
		
		$.post(serviceUrl, queryString, function(json) {
			if(json.status == 'OK') {
				sendOrder();
			} else {
				alert(json.message);
			}
		}, "json"); 
		
	} else {
		sendOrder();
	}

}

function makePayment(id) {
	
	//
	// validate form
	//
	//olddisplay
	var validator = $('#new_individual_form:visible, #new_company_form:visible, #sndeml:visible').validate({
		
		rules: {
			bill_email: { required: true, email: true },
			client_name : { required: true, rangelength: [3, 255] },
			billing_address : { required: true, rangelength: [3, 500] },
			billing_index : { required: true, rangelength: [1, 25] },
			billing_city : { required: true, rangelength: [3, 255] },
			contact_telephone : { required: true, rangelength: [3, 255] },
			contact_email: { required: true, email: true },
			c_password1: { required: true, rangelength: [5, 32] },
			c_password2: { required: true, rangelength: [5, 32] },
			contact_person : { required: true, rangelength: [3, 255] },
			company_name : { required: true, rangelength: [3, 150] },
			billing_email: { required: true, email: true },
			company_reg: { required: true, rangelength: [3, 50] },
			cbilling_address: { required: true, rangelength: [3, 500] },
			cbilling_index: { required: true, rangelength: [1, 25] },
			cbilling_city: { required: true, rangelength: [3, 255] },
			ccontact_telephone: { required: true, rangelength: [3, 255] },
			ccontact_email: { required: true, email: true },
			cc_password1: { required: true, rangelength: [5, 32] },
			cc_password2: { required: true, rangelength: [5, 32] },
			form_login_username: { required: true, email: true },
			form_login_passwd: { required: true, rangelength: [5, 32] },
			form_reminder_email: { required: true, email: true }
		},
		ignore: ".ignore"
	});
	
	if(!validator.form()) {
		$.scrollTo( validator['currentForm'], 800, {offset:-26} );
		return false;
	}
	
	var card_id = null;
	$('input[name=permit_card]').each(function(id, val) {
		if(val.checked) {
			card_id = val.value;
		}
	});
	
	function sendOrder () {
	
		$.post(serviceUrl, {action: "makePayment", id: id, card_id: card_id, confirm_email: $('#bill_email').attr('value') }, function(json){
		
			//Disable buttons
			$('#step_five form button').attr('disabled', 'true');
			
			//
			// Fill in req fields
			//
			
			var form = $('#paymentmethod_' + id);
			
			$.each(json.payment_params, function(i, val) {
				form.append('<input type="hidden" id="pos_' + String(val.name).toLowerCase() + '" name="' + val.name + '" value="' + val.value + '" />');
			});
			
			form.append('<input type="hidden" id="payment_request_id" name="pid" value="' + json.payment_request_id + '" />');
			
			//Submit form
			form.submit();
			
			
		}, "json");
		
	} //send order
	
	//Save contact details if needed
	var new_individual_form = $('#new_individual_form');
	var new_company_form = $('#new_company_form');
	var form_type = '';
	
	$('input[name=client_select]').each(function(id, val) {
		if(val.checked) {
			form_type = val.value;
		}
	});
	
	if(new_individual_form.length || new_company_form.length) {
		
		//
		// Check required fields
		//
		/*
		if($.validationEngine.submitValidation($("#new_individual_form"),{
			validationEventTriggers:"keyup blur"
		})) return false;
		*/
		
		//
		// Send register
		//
		
		var queryString = (form_type == 'COMPANY' ? new_company_form.formSerialize() : new_individual_form.formSerialize() );
		
		$.post(serviceUrl, queryString, function(json) {
			if(json.status == 'OK') {
				sendOrder();
			} else {
				alert(json.message);
			}
		}, "json"); 
		
	} else {
		sendOrder();
	}

	
}

function changeEnd(field_id) {
	
	var prefix = 'End date: ';
	
	var start_date = $('#field_date_2').attr('value');
	var start_time = $('#field_time_2').attr('value');
	var selects = $('select[id^=field_period_' + field_id +']');
	var end_date = $('#field_period_end_'+ field_id);
	
	var period = '';
	selects.each(function(){
		var per = $(this).attr('period');
		var val = $(this).attr('value');
		
		per = per.replace(/\d+/, val);
		
		period += ' +' + per;
		
	});
	
	var d_val = new Date(strtotime(period,strtotime(start_date + ' ' + start_time)) * 1000);
					
	var the_date = '';
	var the_time = '';
	if(d_val) {
		the_date = d_val.toEtDate();
		the_time = d_val.toEtTime();
		try {
			end_date.html(prefix + the_date + ' ' + the_time).animate({backgroundColor: '#FFAE0B'}, 1000).animate({backgroundColor: '#D6D6D6'}, 1000);
		} catch (e) {};
	} else {
		end_date.html(prefix + '');
	}
	
}

function changeForm(type) {
	
	var lis = $('#buyinfo ul.tabs li');
	lis.each(function() {
		$(this).removeClass('selected');
	});
	
	if(type == 'fixed') {
		$('#tab_fixed_period').addClass('selected');
		$('.not_free').show();
		$('#field_6').attr('value', 'fixed');
	} else if(type == 'free') {
		$('#tab_free_period').addClass('selected');
		$('.not_free').hide();
		$('#field_6').attr('value', 'free');
	}
	return false;
}

function changeClient(type) {
	var lis = $('#contact_info ul.tabs li');
	lis.each(function() {
		$(this).removeClass('selected');
	});
	
	if(type == 'new') {
		$('#tab_new_client').addClass('selected');
		$('#new_client_form').show();
		$('#old_client_form').hide();
		$('#forgot_passwd_form').hide();
		$('.formError').hide();
		$("#step_five").show();
	} else if(type == 'old') {
		$('#tab_old_client').addClass('selected');
		$('#new_client_form').hide();
		$('#old_client_form').show();
		$('#forgot_passwd_form').hide();
		$('.formError').hide();
		$("#step_five").hide();
	} else if(type == 'forgot_passwd') {
		$('#tab_forgot_passwd').addClass('selected');
		$('#new_client_form').hide();
		$('#old_client_form').hide();
		$('#forgot_passwd_form').show();
		$('.formError').hide();
		$("#step_five").hide();
		//forgot_passwd_form
		//forgot_passwd
	}
	return false;
}

function changeClientType(type, item) {
	
	if(!item.checked) return false;

	if(type == 'INDIVIDUAL') {
		$('#new_individual_form').show();
		$('#new_company_form').hide();
		$('.formError').hide();
	} else if(type == 'COMPANY') {
		$('#new_individual_form').hide();
		$('#new_company_form').show();
		$('.formError').hide();
	}
	
	return true;
}

//
// Form validation and history
//
var global_hash = '';

$(document).ready(function() { 
	/*
	$("#new_individual_form").validationEngine({
		validationEventTriggers:"keyup blur"
	});
	
	
	$("#new_company_form").validationEngine({
		validationEventTriggers:"keyup blur"
	})
	*/
	
	setInterval(function () {
		var newHash = getHash();
		if (newHash !== global_hash) {
			
			$('#ep-history').attr('value', global_hash);
			
			global_hash = newHash;
			handleStateChange(global_hash);
		}
    }, 50);

	
});

//
// Make IE round corners
//

DD_roundies.addRule('#loginContainer', '10px 10px');
//DD_roundies.addRule('#parkinfo',  '0px 0px 5px 5px');
DD_roundies.addRule('#buyinfo',  '5px 5px');
DD_roundies.addRule('#contact_info',  '5px 5px');
DD_roundies.addRule('.permitDetails', '10px 10px');


