// accipiter v0.1
// front-end javascript functions
// by aquila solutions
// http://aquila-solutions.hu

/* CONTENT VARS */
var runningAnimation = false;
var effectDone;
var loadDone;
var loadDiv;
var language = 'hu';
var languages = Array( 'hu', 'en' );
var responseText;

/* GALLERY VARS */
var galleryRunningAnimation = false;
var galleryEffectDone;
var galleryLoadDone;
var galleryResponseText;
var galleryListItem = 0;
var galleryContainerId;
var galleryImageListItem = 0;

/* PLACEFINDER VARS */
var pfGeocoder;
var pfMap;
var pfFrom;
var pfMarkerTo;
var pfHit;
var pfDirectionDisplay;
var pfDirectionsService;

/* NAVIGATION VARS */
var visitedContents = new Array({
	type: 'content',
	content: 'index'
});

function requestContent( lang, content, params, div ) {
	params = params || {};
	loadDiv = div || 'content_text'
	
	if( runningAnimation ) {
		return;
	}
	
	runningAnimation = true;
	effectDone = false;
	loadDone = false;
	responseText = '';
	
	url = '/ajax/';
	if( lang ) {
		language = lang;
	} else {
		possibleLang = window.location.pathname.substr( 1 );
		for ( i = 0; i < languages.length; i++ ) {
			if ( languages[i] === possibleLang ) {
				language = possibleLang;
			}
		}
	}
	url = url + language + "/";
	if( content ) {
		url = url + content + "/";
	}	
	
	visitedContents.push({
		type: 'content',
		content: content
	});

	hideEffect( loadDiv, {
		afterFinish: function() {
			effectDone = true;
			loadText();
		}
	});
	new Ajax.Request( url, 
		{
			method: 'post',
			parameters: params,
			onSuccess: function(transport) {
				responseText = transport.responseJSON;
				loadDone = true;
				loadText();
			}
		}	
	);	
}

function requestSpecialContent( type, scid, params, div ) {
	params = params || {};
	loadDiv = div || 'content_text'
	
	if( runningAnimation ) {
		return;
	}
	
	visitedContents.push({
		type: 'specialContent',
		specialType: type,
		scid: scid,
		params: params
	});
	

	runningAnimation = true;
	effectDone = false;
	loadDone = false;
	responseText = '';
	
	url = '/ajax/';
	url = url + language + "/specialContent/" + type + '/' + scid + '/';
	
	hideEffect( loadDiv, {
		afterFinish: function() {
			effectDone = true;
			loadText();
		}
	});
	new Ajax.Request( url, 
		{
			method: 'post',
			parameters: params,
			onSuccess: function(transport) {
				responseText = transport.responseJSON;
				loadDone = true;
				loadText();
			}
		}	
	);	
}

function contentClicked( content ) {
	if( runningAnimation ) {
		return;
	}
	requestContent( null, content );
}

function languageClicked( language ) {
	if( runningAnimation ) {
		return;
	}
	requestContent( language, responseText.contentId );
}

function loadText() {
	if( effectDone && loadDone ) {
		galleryListItem = 0;
		galleryImageListItem = 0;
	
		$( loadDiv ).innerHTML = responseText.content;
		showEffect( loadDiv, {
			afterFinish: function() {
				runningAnimation = false;
				eval( responseText.js );
			}
		});
	}
}


/* SPECIAL CONTENTS */
/* GALLERY */
function galleryListPageLeft( elem ) {
	$A( elem.parentNode.parentNode.childNodes ).each( function( elem ) {
		if( elem.className == 'gallery_list_inner' ) {
			if( galleryListItem <= 0 ) {
				return;
			}
			newId = 'toMove' + Math.random();
			elem.id = newId;
			new Effect.Move( newId, {
				x: 200,
				mode: 'relative',
				duration: 0.4,
				queue: {
					scope: 'galleryListPager',
					position: 'end'
				}
			});
			galleryListItem--;
		}
	});
}

function galleryListPageRight( elem ) {
	$A( elem.parentNode.parentNode.childNodes ).each( function( elem ) {
		if( elem.className == 'gallery_list_inner' ) {
			cnt = 0;
			$A( elem.childNodes ).each( function( elem2 ) {
				if( elem2.className == 'gallery_list_item' ) {
					cnt++;
				}
			});
			if( galleryListItem >= ( cnt - 1 ) ) {
				return;
			}
			newId = 'toMove' + Math.random();
			elem.id = newId;
			new Effect.Move( newId, {
				x: -200,
				mode: 'relative',
				duration: 0.4,
				queue: {
					scope: 'galleryListPager',
					position: 'end'
				}
			});
			galleryListItem++;
		}
	});
}

function loadGalleryListItem( galleryId, listId ) {
	requestSpecialContent( 'gallery', galleryId );
}

function loadGalleryText() {
	if( galleryEffectDone && galleryLoadDone ) {
		$( galleryContainerId ).innerHTML = responseText;
		showEffect( galleryContainerId, {
			afterFinish: function() {
				galleryRunningAnimation = false;
			}
		});
	}
}

function imageListPageRight() {
	cnt = 0;
	$A( $( 'images_inner' ).childNodes ).each( function( elem2 ) {
		if( elem2.className == 'image' ) {
			cnt++;
		}
	});

	if( galleryImageListItem >= ( cnt - 1 ) ) {
		return;
	}

	new Effect.Move( 'images_inner', {
    	x: -400,
	    mode: 'relative',
    	duration: 0.4,
		queue: {
			scope: 'galleryImageListPager',
			position: 'end'
	    }
	});
    galleryImageListItem++;
}

function imageListPageLeft() {
	if( galleryImageListItem <= 0 ) {
		return;
	}

	new Effect.Move( 'images_inner', {
    	x: 400,
	    mode: 'relative',
    	duration: 0.4,
		queue: {
			scope: 'galleryImageListPager',
			position: 'end'
	    }
	});
	galleryImageListItem--;
}


/* REGISTRATION */
function registrationInit() {
	Recaptcha.create( "6Lfa-rsSAAAAAApi8jJI_5pniAWxq9WPdx9AtzrH",
		"recaptcha", 
		{  
			theme: "blackglass",
			callback: Recaptcha.focus_response_field 
		}
	);
}

function registration() {
	lastName = $( 'registration_last_name' ).value;
	firstName = $( 'registration_first_name' ).value;
	emailAddress = $( 'registration_email' ).value;
	password = $( 'registration_password' ).value;
	password2 = $( 'registration_password2' ).value;
	birthYear = $( 'registration_birth_year' ).value;
	birthMonth = $( 'registration_birth_month' ).value;
	birthDay = $( 'registration_birth_day' ).value;
	
	if( lastName.length < 2 || lastName.length > 80 ) {
		alert( 'A vezetéknév 2 és 80 karakter közötti lehet!' );
		return;
	}
	if( firstName.length < 2 || firstName.length > 80 ) {
		alert( 'A keresztnév 2 és 80 karakter közötti lehet!' );
		return;
	}
	if( emailAddress.length < 5 || emailAddress.length > 80 ) {
		alert( 'Az email cím 5 és 80 karakter közötti lehet!' );
		return;
	}
	if( password.length < 4 || password.length > 16 ) {
		alert( 'A jelszó 4 és 16 karakter közötti lehet!' );
		return;
	}
	if( password != password2 ) {
		alert( 'Nem egyezik a két jelszó!' );
		return;
	}
	
	requestContent( null, 'registration', { 
		registration_submit: "true",
		first_name: firstName,
		last_name: lastName,
		email: emailAddress,
		password: password,
		birth_date: birthYear + '-' + birthMonth + '-' + birthDay,
		recaptcha_challange: Recaptcha.get_challenge(),
		recaptcha_response: Recaptcha.get_response()
	});
}

function login() {
	emailAddress = $( 'login_email' ).value;
	password = $( 'login_password' ).value;
	
	if( emailAddress.length < 5 || emailAddress.length > 80 ) {
		alert( 'Az email cím 5 és 80 karakter közötti lehet!' );
		return;
	}
	if( password.length < 4 || password.length > 16 ) {
		alert( 'A jelszó 4 és 16 karakter közötti lehet!' );
		return;
	}
	
	requestContent( null, 'login', { 
		login_submit: "true",
		login_email: emailAddress,
		login_password: password
	});
}

function logout() {
	contentClicked( 'logout' );
}

function toggleLoginBox() {
	$A( $$( '.login_box' ) ).each( function( elem ) {
		if( elem.style.display == 'none' ) {
			elem.style.display = '';
		} else {
			elem.style.display = 'none';
		}
	});
}

function lostpassword() {
	emailAddress = $( 'lostpassword_email' ).value;
	
	if( emailAddress.length < 5 || emailAddress.length > 80 ) {
		alert( 'Az email cím 5 és 80 karakter közötti lehet!' );
		return;
	}
	
	requestContent( null, 'lostpassword', { 
		lostpassword_submit: "true",
		lostpassword_email: emailAddress
	});
}


/* NEWSLIST */
function loadNewsListItem( newsId, listId ) {
	requestSpecialContent( 'news', newsId );
}

/* FORUM */
function loadForumItem( topicId, forumId ) {
	requestSpecialContent( 'forumTopic', topicId );
}

function forumTopicComment() {
	comment = $( 'comment' ).value;
	if( comment.length == 0 || comment.length > 1500 ) {
		alert( 'A hozzászólás 1 és 1500 karakter közötti lehet!' );
		return;
	}
	
	requestSpecialContent( 'forumTopic',  $( 'forum_topic_id' ).value, { 
		forum_topic_comment_submit: "true",
		forum_topic_comment: comment
	});
	
}

function deleteForumTopicComment( commentId ) {
	requestSpecialContent( 'forumTopic',  $( 'forum_topic_id' ).value, { 
		forum_topic_comment_delete: "true",
		forum_topic_comment_id: commentId
	});
	
}

/* 18 YEARS WARNING */
function yes18() {
	new Ajax.Request( '/ajax/hu/specialContent/isAdult' );
	$( 'warning' ).style.display = 'none';
}

function no18() {
	window.close();
}

/* PLACEFINDER */
function initPlaceFinder() {
	pfGeocoder = new google.maps.Geocoder();
	pfDirectionsService = new google.maps.DirectionsService();
    pfDirectionsDisplay = new google.maps.DirectionsRenderer();
	var myOptions = {
		zoom: 10,
		center: new google.maps.LatLng( 47.5, 19.1 ),
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	pfMap = new google.maps.Map( document.getElementById( "place_finder_map" ), myOptions );
//	codeAddress( "Budapest" );
    pfDirectionsDisplay.setMap( pfMap );
}

function codeAddress( address ) {
	pfGeocoder.geocode( { 'address': address + ", Budapest, Hungary" }, function( results, status ) {
		if ( status == google.maps.GeocoderStatus.OK ) {
			pfMap.setCenter( results[0].geometry.location );
/*			var marker = new google.maps.Marker({
				map: pfMap, 
				position: results[0].geometry.location
			});*/
		} else {
			alert( "Hiba: " + status );
		}
	});
}

function placeFinderSearch() {
	pfGeocoder.geocode( { 'address': $( 'place_finder_input_start' ).value + ', Budapest, Hungary' }, function( results, status ) {
		if ( status == google.maps.GeocoderStatus.OK ) {
			pfFrom = results[0].geometry.location;
			pfMap.setCenter( results[0].geometry.location );
			pfMap.setZoom( 13 );
			
			url = '/ajax/';
			url = url + language + '/specialContent/placefinder/';
	
			new Ajax.Request( url, 
				{
					method: 'post',
					parameters: { 
						place_finder_find_nearest: true,
						special_content_frame_off : true,
						lat: results[0].geometry.location.lat(),
						lng: results[0].geometry.location.lng()
					},
					onSuccess: function(transport) {
						resp = transport.responseJSON;

//						$( 'place_finder_hit' ).innerHTML = resp.content;

					    var request = {
					        origin: results[0].geometry.location, 
					        destination: new google.maps.LatLng( resp.js.pfHit.lat, resp.js.pfHit.lng ),
					        travelMode: google.maps.DirectionsTravelMode.DRIVING
					    };
					    
					    pfDirectionsService.route( request, function( response, status ) {
					    	if ( status == google.maps.DirectionsStatus.OK ) {
					    		pfDirectionsDisplay.setDirections( response );
					    	} else {
					    		alert( 'Directions hiba! ' + status );
					    	}
					    });
					}
				}	
			);	

		} else {
			alert( "Hiba: " + status );
		}
	});
}

function placeFinderSelected() {
	if( !pfFrom || !$( 'place_finder_another' ).value ) {
		return;
	}
	
	pfMap.setZoom( 13 );

	url = '/ajax/';
	url = url + language + '/specialContent/placefinder/';
	
	new Ajax.Request( url, 
		{
			method: 'post',
			parameters: { 
				place_finder_get_place: $( 'place_finder_another' ).value,
				special_content_frame_off : true
			},
			onSuccess: function(transport) {
				resp = transport.responseJSON;

				$( 'place_finder_hit' ).innerHTML = resp.content;

/*				if( pfMarkerTo ) {
					pfMarkerTo.setMap( null );
				}
						
				pfMarkerTo = new google.maps.Marker({
					map: pfMap, 
					position: new google.maps.LatLng( resp.js.pfHit.lat, resp.js.pfHit.lng )
				});

				pfMap.setCenter( pfMarkerTo.getPosition() );*/
				
			    var request = {
			        origin: pfFrom,
			        destination: new google.maps.LatLng( resp.js.pfHit.lat, resp.js.pfHit.lng ),
			        travelMode: google.maps.DirectionsTravelMode.WALKING
			    };

			    pfDirectionsService.route( request, function( response, status ) {
					if ( status == google.maps.DirectionsStatus.OK ) {
			    		pfDirectionsDisplay.setDirections( response );
			    	}
			    });
			}
		}
	);


}


/* NEWSLETTER */
function newsLetterSubscribeInit() {
	Recaptcha.create( "6Lfa-rsSAAAAAApi8jJI_5pniAWxq9WPdx9AtzrH",
		"recaptcha", 
		{  
			theme: "blackglass",
			callback: Recaptcha.focus_response_field 
		}
	);
}

function newsLetterSubscription() {
	emailAddress = $( 'newsletter_subscription_email' ).value;
	if( emailAddress.length < 5 || emailAddress.length > 80 ) {
		alert( 'Az email cím 5 és 80 karakter közötti lehet!' );
		return;
	}
	
	requestContent( null, 'newsLetter', { 
		newsletter_subscription_submit: "true",
		email: emailAddress
	});
}

/* CALENDAR */
function requestCalendar( year, month ) {
	url = '/ajax/' + language + "/specialContent/calendar/";

	new Ajax.Updater( 'right_bar_calendar', url, 
		{
			method: 'post',
			parameters: { 
				calendar_year: year, 
				calendar_month: month
			}
		}
	);

}

/* EVENTS */
function requestEventDay( eventListId, year, month, day ) {
	requestSpecialContent( 'eventList', eventListId, {
		event_year: year,
		event_month: month,
		event_day: day
	});
}


/* NAVIGATION */
function returnToLastVisited() {
	lastItem = visitedContents.pop();
	lastItem = visitedContents.pop();
	if( lastItem.type == 'content' ) {
		requestContent( null, lastItem.content );
	} else if( lastItem.type == 'specialContent' ) {
		requestSpecialContent( lastItem.specialType, lastItem.scid, lastItem.params );
	}
}
