var Glokaal = function()
{	
	var this_ = this;
	this_.lang = [];
	this_.city = Gcity;
	this_.admin = false;
	this_.init = function()
	{
		
		//$.ajaxSetup({ cache: false });
		
		$( ".datepicker" ).datepicker({
			changeMonth: true,
			changeYear: true,
			yearRange: '-60'
		});
		
		$('#lang_sel a').click(function()
		{
			var langNo = $(this).find('img').attr('src').replace(/[^\d+]/g, '');
			$.getJSON("/index/lang-sel", {langNo: langNo}, function(){document.location.reload();});
			return false;
		});
		
		if($('#search_form input[name=street]').val() == '' && $('#search_form input[name=name]').val() == '') $('#adv_search').hide();
		
		$('#search_form').submit(function()
		{
			if(this_.admin) return true;
			var t = $(this), 
				area = t.find('select[name=area] :selected').text(),
				category = t.find('select[name=category] :selected').text(),
				street = t.find('input[name=street]').val(),
				name = t.find('input[name=name]').val(),
				str = '';
			category = category.substr(0, category.indexOf('(') - 1)
			if(category == 'Alla' || category ==  'Any' || category == 'Kaikki') category = '';
			str = '/' + area + '/' + category + '/' +  name + '/' +  street;
			while(str.substr(-1) == '/') str = str.substr(0, str.length -1);
			document.location = str.replace(' ', '+');
			return false;
		});
		
		$('#search_form select[name=area]').change(function()
		{
			$('#category_holder_div').load('/search/get-category', {area: $(this).val(), category: $('#search_form select[name=category]').val()});
		});
		
		$('#adv_search_link').click(function()
		{
			$('#adv_search').toggle();
			return false;
		});
		
		$('.leave-comment').click(function()
		{
			$(this).hide();
			$('form.comments').show('fast');
			return false;
		});
		
		$('.logout').livequery('click', function(elm)
		{
			$.getJSON("/user/logout/",
				  {},
				  function(transport){
				    this_.checkMessages(transport);
				    setTimeout('location.reload(true);', 500);
				  }
				);
			return false;
		});
		
		if(this_.initExtra != undefined) this_.initExtra();

	};
	
	this_.initMap = function (lat, lng)
	{
		$("#map_canvas").gMap
		({
			latitude: lat,
			longitude: lng,
			markers:
			[{
				latitude: lat,
				longitude: lng,
				icon: 
				{
					image: 'http://www.glokaal.com/img/arrow_down.gif',
					iconsize: [20, 22],
					iconanchor: [10, 22]
				}
			}], 
			zoom: 15,
			controls: ['GSmallMapControl', 'GMapTypeControl'] 
		});
	};
	
	this_.bigMap = function (lat, lng)
	{
		var map = $("#bigmap"), o = map.offset(), w = map.width(), h = map.height();
		$('body').append('<div id="tooltip"></div><img id="ajaxLoad" src="/img/ajax.gif" />');
		this_.tooltip = $('#tooltip');
		this_.ajaxLoad = $('#ajaxLoad').css({top: o.top + h / 2 - 20  + 'px', left: o.left + w / 2 - 20 + 'px'});
		
		this_.map = map.gMap
		({
			icon: 
			{
				image: '/img/marker.png',
				iconsize: [15, 15],
				iconanchor: [7, 7],
				shadow: '/img/marker.png',
				shadowsize: [15, 15],
				infowindowanchor: [9, -2]
			},
			latitude: lat,
			longitude: lng,
			zoom: 11,
			controls: ['GSmallMapControl', 'GMapTypeControl'],
			moveend: this_.show,
			mouseover: this_.mover,
			mouseout: this_.mout,
			click: this_.markerClick
		});
		this_.geocoder = new GClientGeocoder();
		$('select[name=category]').change(this_.show);
		
		$('#move').click(this_.move);
		if($('#search_form').length && !$('#search_form select[name=area]')[0].selectedIndex && !$('#mapForm select[name=area]')[0].selectedIndex)
			this_.show();
		else
			this_.move();
		
		$(document).mousemove(function(e){
			   this_.mx = e.pageX;
			   this_.my = e.pageY;
			   this_.shift = e.shiftKey;
			   this_.alt = e.altKey;
			});
		
	};
	
	this_.show = function()
	{
		this_.tooltip.hide();
		this_.ajaxLoad.show();
		var b = this_.map.getBounds();
		var ne = b.getNorthEast();
		var sw = b.getSouthWest();
		var category = $('#mapForm select[name=category]').val();
		var v = {"lat1":  sw.lat(), "lat2": ne.lat(), "lng1": sw.lng(), "lng2": ne.lng(), "category": category};
		$.getJSON("map/markers", v, this_.markers);
		return false;
	};
	
	this_.markers = function(data)
	{
		var i = 0, limit = 200, markers = [];
		for(var l in data.markers)
		{
			if(i++ > limit)
			{
				//alert(limit + ' markkerii max');
				break;
			}
			var item = data.markers[l];
			/*
        	markers.push({
            	latitude: item.latitude,
				longitude: item.longitude,
				html: item.html,
				id: item.id
        	});
        	*/
			markers.push({
				id: item[0],
            	latitude: item[1],
				longitude: item[2],
				name: item[3][0],
				html: '<div class="item">' +
					'<h2 class="name">' + item[3][0] + '</h2>' +
					'<div class="address">' + item[3][1] + '</div>' +
					'<div class="zipcode">' + item[3][2] + '</div>' +
					'<div class="city">' + item[3][3] + '</div>' +
					'<div class="phone">' + item[3][4] + '</div>' +
					'</div>'
				
        	});
	     }
		this_.map.drawMarkers(markers);
		this_.ajaxLoad.hide();
	};
	
//		console.debug(e, x, v, this, this_);

	
	this_.mover = function(e,x ,v)
	{
		var o = {left: this_.mx, top: this_.my}; //$(this.RB).offset();
		this_.tooltip.html(this.html + '<div class="clear"></div>').css({left: o.left - this_.tooltip.width() / 2 + 'px', top: o.top - this_.tooltip.height() - 25 + 'px'}).show();
		//this.openInfoWindowHtml(this.html);
	};
	
	this_.mout = function()
	{
		this_.tooltip.hide();
	};
	
	this_.markerClick = function()
	{
		document.location = '/page/' + this.id + '/' + this.name;
		return false;
	};
	
	this_.move = function()
	{
		var t = $('#mapForm select[name=area] :selected').text(), loc = (t == 'Keskusta' ? '' : t + ' ') + this_.city + ', finland';
		this_.geocoder.getLocations(loc, this_.moveTo);
		return false;
	};
	
	this_.moveTo = function (response) 
	{
		if (response && response.Status.code == 200) {
			this_.ajaxLoad.show();
		place = response.Placemark[0];
		this_.map.panTo(new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]));
		//this_.show();
		}
	};
	
	this_.checkMessages = function (transport, extra)
	{
		var msg = transport.msg;
		if(msg == undefined) return;
		
		if(msg && msg.length > 0)
		{
			for(var l = 0; l < msg.length; l++)
			{
				var m = msg[l][1];
				switch(msg[l][0])
				{
					case 'e':
					case 'm':
						this_.showMessage(m, msg[l][0]);
						break;
					case 'a':
						switch(m)
						{
							case 'authentication_required':
							case 'show_login':
								//this_.renderLogin('login');
							break;
							
							case 'reload':
								setTimeout('location.reload(true);', msg[l][2]);
							break;
														
							default:
//								console.debug((this_[m]));
								if(this_[m]) this_[m](msg[l][2], extra);
							break;
						}
						break;
				}
			}
		}
	};
	
	this_.showMessage = function(msg, type)
	{
		var message = this_.getLang(msg) != undefined ? this_.getLang(msg) : msg;
		$.prompt(message, {prefix: type}).children('#' + type).corner();
		
		return;
		var tpl = type == 'e'? this_.errTpl : this_.msgTpl;
		$('#messages').html('');
		$('#messages').tplAppend({msg: msg}, tpl);
		$('#messages').center();
	
	};
	
	this_.getLang = function(path)
	{
		if(this_.lang[path] != undefined) return this_.lang[path];
	};
	
	this_.validation_error = function(fields, form)
	{
		if(form != undefined) this_.errorizeForm($(form), fields);
		else this_.errorizeForm($('.ajaxForm'), fields);
	};
	
	$('.ajaxForm').livequery(function() {
		var form = this;
		$(this).ajaxForm({
			dataType: 'json', 
			success: function(transport)
			{
				//console.debug('x'+transport);
				this_.checkMessages(transport, form);
			}
			
	    })
	});
	
	$('table.captcha img').livequery('click', function()
	{
		var img = $(this), table =  img.closest('table.captcha'), hash = table.find('input[name=captchaHash]');
		console.debug(table);
		$.getJSON("/form/new-captcha", {}, function(response)
		{
			console.debug(hash);
			img.attr('src', response.captcha.src);
			hash.val(response.captcha.hash);
		});
	});
	
	this_.errorizeForm = function(form, fields)
	{
		var inps = $(':input', form[0]);
		for(var i = 0; i < inps.length; i++)
		{
			var inp = $(inps[i]);
			var label = inp.parent('label');
			inp.removeClass('error');
			label.removeClass('error');
			var name = inp.attr('name');
			for(var l = 0; l < fields.length; l++)
			{
				if(name == fields[l])
				{
					inp.addClass('error');
					label.addClass('error');
					break;
				}
			}
		}
	
	};
	
	this_.formSubmitOk = function(page, form)
	{
		var s = page.constructor == Array ? page[1] : '#results', p = page.constructor == Array ? page[0] : page;
		$(s).load('/page/' + p + '/plain/1 td');
	}
	
	this_.commentSubmit = function()
	{
		$('.leave-comment').show();
		$('form.comments').hide('fast');
		$('form.comments').get(0).reset();
	}
	
	this_.redirect = function(page, form)
	{
		document.location = page;
	}
	
	this_.formSelect = function(values, selected, attr)
	{
		var a = '';
		if(attr != undefined)
		{
			for(var l in attr)
			{
				a += ' ' + l + '="' + attr[l] + '"';
			}
		}
		var s = '<select' + a + '>\n', sel;
		
		for(var l in values)
		{
			sel = l === selected ? ' selected="selected"' : '';
			s += '<option value="' + l + '"' + sel +'>' + values[l] + '</option>\n';
		}
		s += '</select>';
		return s;
		
	};
	
	
};

glokaal = new Glokaal();


