(function($) {
    $(document).ready(function(){
		var element =  document.getElementById('googlemaps');
		if (typeof(element) != 'undefined' && element != null)
		{
			/* google maps */
			var directionsDisplay = new google.maps.DirectionsRenderer();
			var directionsService = new google.maps.DirectionsService();

			// ===== request the directions =====
			function getDirections() {
				// ==== Set up the walk and avoid highways options ====
				var request = {};
				if (document.getElementById("walk").checked) {
					request.travelMode = google.maps.DirectionsTravelMode.WALKING;
				} else {
					request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
				}

				if (document.getElementById("highways").checked) {
					request.avoidHighways = true;
				}
				// ==== set the start and end locations ====
				var saddr = document.getElementById("saddr").value;
				var daddr = document.getElementById("daddr").value;

				request.origin = saddr;
				request.destination = daddr;
				directionsService.route(request, function(response, status) {
					if (status == google.maps.DirectionsStatus.OK) {
						directionsDisplay.setDirections(response);
					} else alert("Directions not found:" + status);
				});
			}

			function getLocations() {
			    var tmp = [];
			    jQuery.ajax({
					type: "POST",
			        cache: false,
			        async: false,
			        url: '/ajax.php',
			        dataType: 'json',
			        data: {
			            action: 'getLocations'
			        },
			        success: function (response) {
			        	tmp = response;
			        }
			    });
			    return tmp;
			};

			var map = new google.maps.Map(document.getElementById('googlemaps'), {
			  	zoom: 12,
			  	center: new google.maps.LatLng(44.792058, 20.440683),
			  	mapTypeId: google.maps.MapTypeId.ROADMAP
			});

			var infowindow = new google.maps.InfoWindow();

			var marker, i;
			var markers = [];

			var locations = getLocations();
			for (i = 0; i < locations.length; i++) 
			{  
				marker = new google.maps.Marker(
				{
					position: new google.maps.LatLng(locations[i][1], locations[i][2]),
					map: map,
					icon: "/img/pin.png"
				});

				/*markers.push(marker);*/

				google.maps.event.addListener(marker, 'click', (function(marker, i) {
					return function() {
						map.setCenter(marker.getPosition());
						map.setZoom(16);
					  	infowindow.setContent(locations[i][0]+", "+locations[i][3]);
					  	infowindow.open(map, marker);
					}
				})(marker, i));
				markers.push(marker);
			}
			$('body').on('click', '.gLoc', function(){
				var id = $(this).attr('data-id');
			    google.maps.event.trigger(markers[id], 'click');
			    $('html, body').animate({
			        scrollTop: $("#googlemaps").offset().top
			    }, 500);
			})
		}
		var homeMap =  document.getElementById('homeMap')
		if (typeof(homeMap) != 'undefined' && homeMap != null)
		{
			/* google maps */
			var directionsDisplay = new google.maps.DirectionsRenderer();
			var directionsService = new google.maps.DirectionsService();

			// ===== request the directions =====
			function getDirections() {
				// ==== Set up the walk and avoid highways options ====
				var request = {};
				if (document.getElementById("walk").checked) {
					request.travelMode = google.maps.DirectionsTravelMode.WALKING;
				} else {
					request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
				}

				if (document.getElementById("highways").checked) {
					request.avoidHighways = true;
				}
				// ==== set the start and end locations ====
				var saddr = document.getElementById("saddr").value;
				var daddr = document.getElementById("daddr").value;

				request.origin = saddr;
				request.destination = daddr;
				directionsService.route(request, function(response, status) {
					if (status == google.maps.DirectionsStatus.OK) {
						directionsDisplay.setDirections(response);
					} else alert("Directions not found:" + status);
				});
			}

			var map = new google.maps.Map(document.getElementById('homeMap'), {
			  	zoom: 14,
			  	center: new google.maps.LatLng(44.81438900, 20.42692200),
			  	mapTypeId: google.maps.MapTypeId.ROADMAP
			});

			var infowindow = new google.maps.InfoWindow();

			var marker, i;
			var markers = [];
			marker = new google.maps.Marker(
			{
				position: new google.maps.LatLng(44.81438900, 20.42692200),
				map: map,
				icon: "/img/pin.png"
			});
			google.maps.event.addListener(marker, 'click', (function(marker, i) {
				return function() {
					map.setCenter(marker.getPosition());
					map.setZoom(16);
				  	infowindow.setContent(locations[i][0]+", "+locations[i][3]);
				  	infowindow.open(map, marker);
				}
			})(marker, i));
		}
		$('#eBookSubmit').on('click',function(){
        	$('#eBookError').empty().addClass('hidden');
            $.ajax({
                type: "POST",
                cache: false,
                url: '/ajax.php',
                dataType: 'json',
                data: {
                    'action':'eBook', 
                    'first_name': $( "#first_name" ).val(),
                    'last_name': $( "#last_name" ).val(),
                    'email': $( "#email" ).val(),
                    'company': $( "#company" ).val(),
                    'address': $( "#address" ).val(),
                    'position': $( "#position" ).val(),
                    'year': $( "#year" ).val(),
                    'hon_cap': $( "#hon_cap" ).val()
                },
                success: function (response) {
					if(response.fieldError)
                    {
                        $(".error").removeClass("error");
                        $('span').find('.errorMsg').remove();
                        var anim;
                        $.each(response.fieldError, function(i, obj) {
                            $('#'+obj.field).addClass('error');
                            //check box field : set span after label
                            var attribute = $('#'+obj.field).attr('type');                                    
                            if( attribute == 'checkbox'){
                               $('#'+obj.field).parent().after('<span class="errorMsg">'+obj.msg+'</span>'); 
                               anim = ".form-item.checkbox";
                            } else {
                                $('#'+obj.field).after('<span class="errorMsg">'+obj.msg+'</span>');  
                                anim = "input.error";  
                            }                                
                        });
                        $('html, body').animate({
                            scrollTop: $(anim).offset().top-50
                        }, 1000);
                    } else if (response.status == 'ok') {
						var lang = $('body').attr('data-lang');
            			var thankYou = (lang == 'en') ? '/en/thank-you' : '/sr/hvala-na-popunjenoj-prijavi';
            			window.location.href = thankYou;
		            }                                                            
                },
                error: function (response) {
                    console.log('error: '+response);
                }
            });
            return false;
	    })
/*	    $('#virtualClassForm').validate({
	        errorPlacement: function(label, element) {
	            element.parent().append( label );
	        },
	        submitHandler: function() {
	        	$('#virtualClassError').empty().addClass('hidden');
	            $.ajax({
	                type: "POST",
	                cache: false,
	                url: '/ajax.php',
	                data: {
	                    'action':'virtualClass', 
	                    'first_name': $( "#first_name" ).val(),
	                    'last_name': $( "#last_name" ).val(),
	                    'email': $( "#email" ).val(),
	                    'company': $( "#company" ).val(),
	                    'city': $( "#city" ).val(),
	                    'date1': $( "#date1" ).val(),
	                    'date2': $( "#date2" ).val(),
	                    'hon_cap': $( "#hon_cap" ).val()
	                },
	                success: function (response) {
	            		if (response.indexOf('sent:') >= 0)
	            		{
	            			$('#virtualClassForm').fadeOut();
	            			$('#virtualClassSuccess').removeClass('hidden');
	            			$('#virtualClassSuccess').show();
	            			$('#virtualClassForm').find('input, textarea, select').val('');
	            			//$('html, body').animate({ scrollTop: 0 }, 'slow');
	            		}
	            		else
	            		{
	            			$('#virtualClassError').removeClass('hidden');
	            			$('#virtualClassError').fadeIn();
	            		}                              
	                },
	                error: function (response) {
	                    console.log('error: '+response);
	                }
	            });
	            return false;
	        }
	    });*/
	    $('input').on('focus', function(){
	    	$(this).removeClass('error');
	    })
	    $('#regSubmit').on('click', function(){
	        	//$('#regError').empty().addClass('hidden');
	            $.ajax({
	                type: "POST",
	                cache: false,
	                url: '/ajax.php',
	                dataType: 'json',
	                data: {
	                    'action':'reg', 
	                    'first_name': $( "#first_name" ).val(),
	                    'last_name': $( "#last_name" ).val(),
	                    'email': $( "#email" ).val(),
	                    'phone': $( "#phone" ).val(),
	                    'course': $( "#course" ).val(),
	                    'course_title': $( "#course option:selected" ).text(),
	                    'comment': $( "#comment" ).val(),
	                    'hon_cap': $( "#hon_cap" ).val()
	                },
	                success: function (response) {
		            	if(response.fieldError)
	                    {
	                        $(".error").removeClass("error");
	                        $('span').find('.errorMsg').remove();
	                        var anim;
	                        $.each(response.fieldError, function(i, obj) {
	                            $('#'+obj.field).addClass('error');
	                            //check box field : set span after label
	                            var attribute = $('#'+obj.field).attr('type');                                    
	                            if( attribute == 'checkbox'){
	                               $('#'+obj.field).parent().after('<span class="errorMsg">'+obj.msg+'</span>'); 
	                               anim = ".form-item.checkbox";
	                            } else {
	                                $('#'+obj.field).after('<span class="errorMsg">'+obj.msg+'</span>');  
	                                anim = "input.error";  
	                            }                                
	                        });
	                        $('html, body').animate({
	                            scrollTop: $(anim).offset().top-50
	                        }, 1000);
	                    } else if (response.status == 'ok') {
							var lang = $('body').attr('data-lang');
	            			var thankYou = (lang == 'en') ? '/en/thank-you' : '/sr/hvala-na-popunjenoj-prijavi';
	            			window.location.href = thankYou;
			            }                     
	                },
	                error: function (response) {
	                    console.log('error: '+response);
	                }
	            });
	            return false;
	        
	    });
	    function getVirtualClassOptions(selector,date)
	    {
	    	$.ajax({
	            type: "POST",
	            cache: false,
	            url: '/ajax.php',
	            data: {
	                'action':'virtualClassOptions', 
	                'date': date
	            },
	            success: function (response) {
	        		$(selector).empty();
	        		$(selector).html(response);                              
	            },
	            error: function (response) {
	                console.log('error: '+response);
	            }
	        });
	    }		
    });
}(jQuery));