$(document).ready( function()
{
	var AUTH_RESULT =
	{
		"0"	: 'Autentificare esuata'
	,	"-1": 'Utilizatorul nu a fost gasit'
	,	"-2": 'Utilizator invalid'
	,	"-3": 'Parola gresita'
	,	"-4": 'Eroare de sistem'
	,	"1" : 'Autentificarea reusita'
	}
	var REGISTER_RESULT =
	{
		"-1": 'Email invalid'
	,	"-2": 'Email deja existent'
	,	"-3": 'Parola inexistenta'
	,	"-4": 'Eroare de sistem'
	,	"1" : 'Inregistrare reusita'
	}
	var RESET_RESULT =
	{
		"-1": 'Email invalid'
	,	"-2": 'Eroare de sistem'
	,	"-3": 'Eroare de sistem'
	,	"1" : 'Resetare cu success'
	}
	
	var ie6=($.browser.msie && $.browser.version=='6.0')?true:false;
	if(ie6)	location.href='ie6.html';

	// submenus
	$('.input').bind('mouseover',function()
	{
		$(this).siblings('.menubox').css({'display':'block'});
		$(this).parent().removeClass('nobg');
		$(this).children('.menubox').bind('mouseleave',function(){
			$(this).css({'display':'none'});
			$(this).parent().addClass('nobg');
		});
		$('.inputc').bind('mouseleave',function(){
			$(this).children('.menubox').css({'display':'none'});
			$(this).addClass('nobg');
		});
	});

	$( '#login .reset-toggle, #login .register-toggle, #login .login-toggle' ).click( function( event )
	{
		event.preventDefault()
	});
		
	$( '#login .reset-toggle' ).click( function()
	{
		var loginForm = $(this).parents( 'form' );
		loginForm.attr( 'action', $(this).attr( 'href' ) );
		loginForm.find( '#data-users-pass' ).parent().hide();
		loginForm.find( 'button' ).text( 'Trimite' )
		loginForm.find( 'h3' ).text( 'Reseteaza-ti parola' )
		$( '#login #login-options' ).hide();
		$( '#login #reset-options' ).show();
		$( '#login #register-options' ).hide();
	});
	
	$( '#login .register-toggle' ).click( function()
	{
		var loginForm = $(this).parents( 'form' );
		loginForm.attr( 'action', $(this).attr( 'href' ) );
		loginForm.find( '#data-users-pass' ).parent().show();
		loginForm.find( 'button' ).text( 'Creeaza cont' )
		loginForm.find( 'h3' ).text( 'Inregistreaza-te' )
		$( '#login #login-options' ).hide();
		$( '#login #reset-options' ).hide();
		$( '#login #register-options' ).show();
	});
	
	$( '#login .login-toggle' ).click( function()
	{
		var loginForm = $(this).parents( 'form' );
		loginForm.attr( 'action', $(this).attr( 'href' ) );
		loginForm.find( '#data-users-pass' ).parent().show();
		loginForm.find( 'button' ).text( 'Intra in cont' )
		loginForm.find( 'h3' ).text( 'Intra in cont' )
		$( '#login #login-options' ).show();
		$( '#login #reset-options' ).hide();
		$( '#login #register-options' ).hide();
	});
	
	$( '#login .login-toggle' ).parents( 'form' ).submit( function(evt)
	{
		var thisForm = $(this);
		$.ajax
		({
			url 	: thisForm.attr('action')
		,	data 	: thisForm.serialize()+'&format=json'
		,	type	: thisForm.attr('method')
		,	dataType: 'json'
		,	success	: function( data )
			{
				var errorMsg = thisForm.find( '.error' ).removeClass( 'success' );
				if( data.result > 0 )
					errorMsg.addClass( 'success' );
				
				eval( "var resMsgs = "+data.action.toUpperCase()+"_RESULT;" );
				errorMsg.html( resMsgs[data.result]+'!' )
				
				if( data.action == 'auth' ) // TODO quick fix :D
					$( '#logout-ctrl' ).show();
			}
		})
		evt.preventDefault();
	});
	
	$('#logout-ctrl').bind( 'click', function( evt, dontPrevent )
	{
		if( dontPrevent == undefined )
		{	
			evt.preventDefault();
			if( FB.getSession() )
				FB.logout();
			else
				$(this).trigger( 'fb.logout' )
		}
		else
			document.location.href = $(this).attr( "href" );
	})
	.bind( 'fb.logout', function()
	{
		var e = jQuery.Event("click");
		$(this).trigger( e, [ true ] )
	});

	// rating, generic
	var removeThanks ='';
	$('.rating:not(.ignore)').each(function()
	{
		var t = $(this);
		for(var i=1;i<=5;i++)
			$(document.createElement('a')).attr('href', '#').addClass('vot-'+i).appendTo(t);

		t.addClass('active').find('a').click(function(){
			t.addClass('votat');
			
			$.ajax
			({
				type: "GET",
				url: "vot.php",
				data: { nota:t.find('a').index(this), id:t.attr('id') },
				dataType:'json',
				cache: false,
				success: function(data){
					t.addClass('votat').find('span').width(data.votNou+'%');
				}
			});
			return false;
	});
		
});

function commentCtrlHandler()
{
	var thisA = $(this);
	thisA.addClass( 'loading' );
	var action = thisA.attr( 'class' ).split( " " );
	action = action[0];
	$.ajax
	({
		url : BASE_URL + '/spots/rate-comment/id/'+thisA.parents( '[id-comment]' ).eq(0).attr( 'id-comment' )+'/rate/'+action+'/format/json'
	,	dataType : 'json'
	,	success : function( data )
		{
			if( data.success )
			{
				thisA.trigger( 'ajax-success' );
				return true;
			}
				thisA.trigger( 'ajax-error' );
		}
	,	error : function( data )
		{
			thisA.trigger( 'ajax-error' );
		}
	});
}

function spotRatingCtrlHandler()
{
	var thisA = $(this);
	thisA.addClass( 'loading' );
	var action = thisA.attr( 'class' ).split( " " );
	action = action[0];
	$.ajax
	({
		url : BASE_URL + '/spots/rate/id/'+thisA.parents( '[id-spot]' ).eq(0).attr( 'id-spot' )+'/rate/'+action+'/rate-id/'+thisA.parents( '[id-rate]' ).eq(0).attr( 'id-rate' )+'/format/json'
	,	dataType : 'json'
	,	success : function( data )
		{
			if( data.success )
			{
				thisA.trigger( 'ajax-success' );
				return true;
			}
			thisA.trigger( 'ajax-error' );
		}
	,	error : function( data )
		{
			thisA.trigger( 'ajax-error' );
		}
	});
}

	$('.recomandare-box .comment-ctrls a')
		.bind( 'ajaxSend', function(){ $(this).unbind('click'); } )
		.bind( 'ajaxComplete', function(){ $(this).removeClass( 'loading' ).click( commentCtrlHandler ) } )
		.click( commentCtrlHandler );
	$('.recomandare-box .comment-ctrls a.delete').bind( 'ajax-success', function()
	{ 
		$(this).parents( '.recomandare-box' ).eq(0).fadeOut( 'fast', function(){ $(this).remove() } ); 
	});
	
	$('#spot-rating .spot-ctrls a')
		.bind( 'ajaxSend', function(){ $(this).unbind('click'); } )
		.bind( 'ajaxComplete', function(){	$(this).removeClass( 'loading' ).click( spotRatingCtrlHandler ) } )
		.click( spotRatingCtrlHandler );
	
}); // document.ready


function antiSpam( mail, domain ) 
{
	document.write( '<a href="mailto:'+mail+'@'+domain+'">'+mail+'@'+domain+'</a>' );
}

var fbObject = 
{
	checkLogin : function( response )
	{
		if( !response.session ) return false;
        $.ajax
        ({ 
        	url : BASE_URL + '/users/check-login/tok/' + response.session.access_token + '/uid/' + response.session.uid + '/format/json'
        ,	dataType : 'json'
        ,	success : function( data )
        	{
        		if( data.error )
        		{
        			if( fbObject.callbacks.loginError )
        				fbObject.callbacks.loginError();
        			return false;
        		}
        		if( fbObject.callbacks.loginSuccess )
        			fbObject.callbacks.loginSuccess( data );
        		var replaceDiv = $( '<div class="fb-profile" />' );
        		replaceDiv.append( $( '<img src="https://graph.facebook.com/me/picture?access_token='+data.authUser.token+'" />' ) )
        			.append( '<span>Salut <br /> ' + data.authUser.name + '</span>' );
        		$( 'fb\\:login-button' ).parents( 'div#login' ).html( '' ).append( replaceDiv )
        		$( '#login #header' ).show();
        		$( '#logout-ctrl' ).show();
        	}
        ,	error : function()
        	{
        		if( fbObject.callbacks.loginError )	fbObject.callbacks.loginError();
        	}
        })
	}
, 	callbacks : {}
,	init : function( appId )
	{
		window.fbAsyncInit = function() 
		{
			FB.init( { appId: appId, status: true, cookie: true, xfbml: true } );
			FB.Event.subscribe( 'edge.create', function( href, widget )
			{ 
			});
			FB.Event.subscribe( 'auth.login', function( response )
			{
				fbObject.checkLogin( response )
			})
			FB.Event.subscribe( 'auth.logout', function( response )
			{
				$('#logout-ctrl').trigger( 'fb.logout' )
			})
			FB.Event.subscribe( 'auth.sessionChange', function( response )
			{
			});
			FB.getLoginStatus( function( response ) 
			{
				fbObject.checkLogin( response )
	        });
		};
		var e = $( '<script />' );
	 	e.attr( 'type', 'text/javascript' );
	 	e.attr( 'src', document.location.protocol + '//connect.facebook.net/en_US/all.js' );
	 	e.get(0).async = true;
		$( 'body' ).append( $( '<div id="fb-root" />').append( e ) );
	}
}

function mapControls( map, x, y, draggable )
{
	var markerOptions = { draggable : draggable };
	var icon = new GIcon( G_DEFAULT_ICON );
	icon.image = "http://"+SERVER_NAME+"/"+BASE_URL+"/images/map-marker.png";
	markerOptions.icon = icon
	var marker		= new GMarker( new GLatLng( y, x ), markerOptions );
	map.addOverlay( marker );
	$(map).data( "marker", marker );
	function CustomZoomControl(){}
	CustomZoomControl.prototype = new GControl();
	CustomZoomControl.prototype.initialize = function(map) 
	{
		var container = document.createElement( "div" );
		container.style.width = '22px';
		container.style.height = '46px';
		var zoomInImg = document.createElement( "img" );
		$(zoomInImg).attr( 'src', BASE_URL + '/images/gmaps/zoom-in.png' );
		this._zoomButtonStyle( zoomInImg );
		container.appendChild( zoomInImg );
		GEvent.addDomListener( zoomInImg, "click", function() 
		{
			map.zoomIn();
		});
		var zoomOutImg = document.createElement( "img" );
		$(zoomOutImg).attr( 'src', BASE_URL + '/images/gmaps/zoom-out.png' );
		this._zoomButtonStyle( zoomOutImg );
		container.appendChild( zoomOutImg );
		GEvent.addDomListener( zoomOutImg, "click", function() 
		{
			map.zoomOut();
		});
		map.getContainer().appendChild(container);
		return container;
	}

	CustomZoomControl.prototype.getDefaultPosition = function() 
	{
		return new GControlPosition( G_ANCHOR_TOP_LEFT, new GSize( 9, 6 ) );
	}

	CustomZoomControl.prototype._zoomButtonStyle = function( button ) 
	{
		button.style.background = "none";
		button.style.border = "none";
		button.style.padding = "0";
		button.style.margin = "0";
		button.style.width = "22px";
		button.style.height = "23px";
		button.style.cursor = "pointer";
	}
	map.addControl( new CustomZoomControl() );	
}
function initMap( x, y, z )
{
	var map = new GMap2( $("#map").get(0) );
	map.checkResize();
	var city = new GLatLng( y, x );
	map.setCenter( city, z );
	mapControls( map, x, y )
	
	function CustomControl(){}
	CustomControl.prototype = new GControl();
	CustomControl.prototype.initialize = function( map ) 
	{
		var container = document.createElement( "div" );
		$(container).css
		({
			margin : 0
		,	padding : 0
		,	width : 118
		,	height : 118
		,	background : 'transparent url('+BASE_URL + '/images/gmaps/pop-out.png) no-repeat center'
		});
		var ctrlA = document.createElement( "a" );
		$(ctrlA).css
		({
			width : 30
		,	height : 30
		,	display : 'block'
		,	margin : '88px 0 0 88px'
		})
		container.appendChild( ctrlA );
		GEvent.addDomListener( ctrlA, "click", function() 
		{
			var bigMap = initBigMap( x, y, z );
			$.fancybox
			({
				'orig'			: $( '#map' )
			,	'hideOnContentClick' : false
			,	'content'		: bigMap.getContainer()
			,	'autoDimensions': false
			,	'width'			: '75%'
			,	'height'		: '75%'
			,	'padding'		: 0
			,	'title'   		: null
			,	'transitionIn'	: 'elastic'
			,	'transitionOut'	: 'elastic'
			,	'speedIn'		: 200
			, 	'speedOut'		: 200
			,	'onComplete'	: function(){ bigMap.checkResize(); bigMap.setCenter( city ) }
			,	'onClosed'		: function(){ $('#fancybox-inner').html( '' ) }
			});
		});
		map.getContainer().appendChild( container );
		return container;
	}

	CustomControl.prototype.getDefaultPosition = function() 
	{
		return new GControlPosition( G_ANCHOR_BOTTOM_RIGHT, new GSize( 0, 0 ) );
	}

	CustomControl.prototype._buttonStyle = function( button ) 
	{
		button.style.background = "none";
		button.style.border = "none";
		button.style.padding = "0";
		button.style.margin = "0";
		button.style.width = "118px";
		button.style.height = "118px";
		button.style.cursor = "pointer";
	}
	map.addControl( new CustomControl() );
	
	$(document).data( "map", map );
}

function initBigMap( x, y, z )
{
	var bigMap = new GMap2( $("<div class='big-map' id='big-map' style='width:100%; height: 100%' />" ).get(0) );
	bigMap.checkResize();
	var city = new GLatLng( y, x );
	bigMap.setCenter( city, z );
	mapControls( bigMap, x, y );
	$(document).data( "big-map", bigMap );
	return bigMap;
}

function initAddMap( selector, x, y, z, inx, iny )
{
	var map = new GMap2( $(selector).get(0) );
	map.checkResize();
	var city = new GLatLng( y, x );
	map.setCenter( city, z );
	mapControls( map, x, y, true )
	$(document).data( "add-map", map );
	var marker = $(map).data( 'marker' );
	GEvent.addListener( marker, "dragend", function() 
	{
		var coords = marker.getLatLng();
		inx.val( coords.x );
		iny.val( coords.y );
	});
	GEvent.trigger( marker, 'dragend' );
	return map;
}

