/*
	DOCUMENT READY
*/
$(document).ready(function(){

	/*	
			MAIN-ANI flash embed
	*/
	$('#main-ani').wrapInner('<div id="main-ani-flash"></div>');
	swfobject.embedSWF(HP_host	+ '/pub/uploadflash/' + $('body').attr('id') + '.swf', 'main-ani-flash', '935', '100%', '8.0.0', '', {HP_host: HP_host});
	
	/*
		CONTACT form ajax submit
	*/
	$('form#career').css({visibility: 'visible'}).submit(function(){
		$this = $(this);
		$this.find('.warning').removeClass('warning');
		if ($.trim($('#f_name').val()) == ''){
			$('label[for="f_name"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_mail').val()) == ''){
			$('label[for="f_mail"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_birthdate').val()) == ''){
			$('label[for="f_birthdate"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_cv').val()) == ''){
			$('label[for="f_cv"]').parent('div').addClass('warning');
		}
		if ($.trim($('#f_lm').val()) == ''){
			$('label[for="f_lm"]').parent('div').addClass('warning');
		}
		if ($('.warning').size()){
			alert('Please fill in all required fields (*) .');
			$('.warning:first label').next().focus();
			return false;
		}
		$this.addClass('processing').find('#unique_id').val((Math.random()) * 10);
		AIM.submit($this.get(0), {
			'onComplete': function(){
				$this.removeClass('processing').html('<p><strong>Your Form has been sent - Thank you .</strong></p>');
			}
		});
		$this.unbind('submit').submit();
		return false;
	});
	
	/*
		AJAX IFRAME METHOD (AIM) http://www.webtoolkit.info/
	*/
	AIM = {
		frame : function(c) {
			var n = 'f' + Math.floor(Math.random() * 99999);
			var d = document.createElement('DIV');
			d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
			document.body.appendChild(d);
			var i = document.getElementById(n);
			if (c && typeof(c.onComplete) == 'function') {
				i.onComplete = c.onComplete;
			}
			return n;
		},
		form : function(f, name) {
			f.setAttribute('target', name);
		},
		submit : function(f, c) {
			AIM.form(f, AIM.frame(c));
			if (c && typeof(c.onStart) == 'function') {
				return c.onStart();
			} else {
				return true;
			}
		},
		loaded : function(id) {
			var i = document.getElementById(id);
			if (i.contentDocument) {
				var d = i.contentDocument;
			} else if (i.contentWindow) {
				var d = i.contentWindow.document;
			} else {
				var d = window.frames[id].document;
			}
			if (d.location.href == "about:blank") {
				return;
			}
			if (typeof(i.onComplete) == 'function') {
				i.onComplete(d.body.innerHTML);
			}
		}
	}
	
	/*
		CLIENTS rollover and preloading
	*/
	
	$('#clients li a img').each(function(){
		image = new Image();
		image.src = $(this).attr('src').replace('grayscale_', '');
	}).hover(function(){
		$(this).attr('src', $(this).attr('src').replace('grayscale_', ''));
	},function(){
		$this = $(this);
		parts = $this.attr('src').split('gtx/');
		$this.attr('src', parts[0] + 'gtx/grayscale_' + parts[1]);
	});
	
	/*
		TEXT INPUTS value show/hide
	*/
	var $directions = $('#directions input:text[value]');
	var startVal = $directions.val();
	$directions.focus(function(){
		(this.value == startVal) && $directions.val('');
	})
	.blur(function(){
		(!this.value) && $directions.val(startVal);
	});
	
	/*
		GOOGLE MAPS
	*/
	if ($('#map').size() && GBrowserIsCompatible()) {
	
		infoText = Array();
		infoText['Poznań'] = $('#map-content li:eq(0)').html();
		infoText['Warszawa'] = $('#map-content li:eq(1)').html();
		infoText['Szczecin'] = $('#map-content li:eq(2)').html();
		$('#map-content').remove();
		
		$('#contact-chooser li a').click(function(e){
			$chooser = $(this);
			$chooser.addClass('active').parent('li').siblings().find('a').removeClass('active');
			showLoc($chooser.text());
			e.preventDefault();
		});
		
		var map = new GMap2(document.getElementById('map'));
		map.addControl(new GSmallMapControl());
		
		var path = [];
		marker = '';
		var showLoc = function(office){
			map.removeOverlay(marker);
			if (office == 'Poznań') {
				lat = 52.412106;
				lng = 16.92019;
				$('#directions label span').text('Poznaniu');
			}
			else if (office == 'Warszawa') {
				lat = 52.228049;
				lng = 21.00749;
				$('#directions label span').text('Warszawie');
			}
			else if (office == 'Szczecin') {
				lat = 53.422321;
				lng = 14.552057;
				$('#directions label span').text('Szczecinie');
			}
			map.setCenter(new GLatLng(lat, lng), 13);
		
			var latlng = new GLatLng(lat, lng);
			marker = new GMarker(latlng);
			GEvent.addListener(marker, 'click', function(){
				map.openInfoWindowHtml(latlng, infoText[office]);
			});
			map.openInfoWindowHtml(latlng, infoText[office]);
			map.addOverlay(marker);
			
			path[1] = latlng;
		}
		
		$('#contact-chooser li:first a').click();
		
		var bounds = new GLatLngBounds();
		var geo = new GClientGeocoder(new GGeocodeCache());
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Nierozpoznany adres.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Nierozpoznany adres - spróbuj wpisać tylko nazwę miejscowości.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Niedostępny adres - nie można pokazać tej trasy.";
		reasons[G_GEO_BAD_KEY]            = "Błędny klucz API.";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Bład - za dużo zapytań. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_SERVER_ERROR]       = "Błąd serwera. Spróbuj ponownie za jakiś czas.";
		reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
		reasons[G_GEO_MISSING_QUERY]      = "Brak lokalizacji w polu wyszukiwania.";
		reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Nie można ustalić połączenia między punktami.";
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.iconSize=new GSize(24,38);
		
		var icon1 = G_START_ICON;
		var icon3 = G_END_ICON;
		var addresses = [];
		var startpoint = null;		

		GEvent.addListener(map, 'click', function(overlay, point){
			if (point)
				doStart(point);
		});
		
		function doStart(point){
			if (startpoint != null){
				map.removeOverlay(startpoint);
				map.setCenter(new GLatLng(lat, lng),12);
				bounds = new GLatLngBounds();
			}
			startpoint = new GMarker(point,{dragable:true, icon:icon1}); 

			GEvent.addListener(startpoint, 'dragend', function(){
				path[0] = startpoint.getPoint();
				addresses[0] = '';
			});
			map.addOverlay(startpoint);

			path[0] = point;
			bounds.extend(path[0]);
			bounds.extend(path[1]);
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			directions();
		}

		var gdir = new GDirections(null, document.getElementById('path'));

		GEvent.addListener(gdir,'error', function(){
			var code = gdir.getStatus().code;
			var reason = 'Kod ' + code;
			if (reasons[code]){
				reason = "Kod " + code + ': ' + reasons[code]
			}
			alert('Failed to obtain directions, ' + reason);
		});

		var poly;
		GEvent.addListener(gdir, 'load', function(){
			if (poly)
				map.removeOverlay(poly);
			poly = gdir.getPolyline();
			map.addOverlay(poly);
		});
		
		GEvent.addListener(gdir, 'addoverlay', function(){
			$('#article tr td:has("a")').each(function(){
				$(this).html($(this).text());
			});
			$('#article tr td').css('cursor', 'default');
		});

		function directions(){
			if (addresses[0]){
				var a = addresses[0] + "@" + path[0].toUrlValue(6)
			}
			else {
				var a = path[0].toUrlValue(6)
			}
			var b = path[1].toUrlValue(6)
			var a = 'from: ' + a + ' to: ' + b;
			gdir.load(a, {getPolyline:true});
			map.removeOverlay(marker);
			var latlng = new GLatLng(lat, lng);
			marker = new GMarker(latlng,{icon:icon3});
			map.addOverlay(marker);
		}
		
		function showAddress(){
			var search = $('#search').val();
			addresses[0] = search;
			geo.getLatLng(search, function (point){ 
				if (point){
					doStart(point);
				}
				else {
					var result = geo.getCache().get(search);
					if (result){
						var reason = 'Code ' + result.Status.code;
						if (reasons[result.Status.code]){
							reason = reasons[result.Status.code]
						}
					}
					else {
						var reason = '';
					}
					alert('Can not find "' + search + '". ' + reason);
				}
			});
		}
		
		$('#directions').show().submit(function(){
			showAddress();
			return false;
		});
	}

});
