//
// SITE Javascript
// © Julian Fann, Pajama Collective
// Client: Uncommon Journeys
// ----------------------------------------
//

// Request form ajax submit
function validateAndSubmit(the_form, callback) {
    
    // Form submit handler
	    $(the_form).validate({
    	    onfocusout: false,
    	    onkeyup: false,
    	    onclick: false,
    	    focusInvalid: true,
    	    focusCleanup: false,
    	    submitHandler: function(form) {
	    
	    // SETUP
	    // ---------------------------------
	    
	        var container = the_form.closest(".ajax_form_container");
	    
    	    // Replace button with loader image
            var button = the_form.children('#submit_button');
        
            // Check if a loading image exists
            if(the_form.children('.ajax_loader').length == 0) {
                // add hidden ajax loading image
                button.after('<img class="ajax_loader" src="/static/images/ajax-loader.gif" alt="Loading" />');
            };
        
            // Assign reusable variable to the loader image
            var loader = the_form.children('.ajax_loader');
        
            // Hide the submit button and show the loading image
            button.hide(0, function(){
                loader.show();
            });

            // Remove any previous errors
        	$('.ajax_response.error').remove(); 

    	// AJAX SUBMIT
    	// ---------------------------------
    	
        	// Grab the action from the form
        	var action = the_form.attr('action'); 
    	
        	// Serialize the form
        	var form_data = the_form.serialize(); 
    	
        	// Submit via a post request
        	$.post(action, form_data, function(data) { 
    	    
        	    // Parse the JSON response into a JS Object
        		data = $.parseJSON(data); 
    		
        		// Success actions
        		if (data.success) {
        		    loader.remove(); // Remove the loading image
        		    // Empty the modal
        			container.empty(); 
        			// Inject the success message
        			container.html('<h3 class="ajax_response success">Thank you for your request.</h3>');
        			
        			// Fire optional callback
                    if (arguments.length == 2) {
                        callback();
                    };
        			
        		};
        		// Error actions
        		if (data.errors) {
        		    loader.remove(); // Remove the loading image
        		    button.show(); // Bring back the submit button
    		    
    		        // Iterated over errors and append an error message to the form
    		        $(data.errors).each(function(index, Element){
    		            container.append('<h3 class="ajax_response error">Error: '+data.errors.Element+'</h3>');
    		        });
        		    // // This could be abstracted more.
        		    //                    // For now, just define an error action for each field.
        		    //                    if (data.errors.email) {
        		    //                        // Inject error message
        		    //                        $("#request_form_container").append('<h3 id="stf_error_email" class="ajax_response error">Error: '+data.errors.email+'</h3>');
        		    //                    };
        		    //                    if (data.errors.friend_email) {
        		    //                        // Inject error message
        		    //                        $("#request_form_container").append('<h3 id="stf_error_friend_email" class="ajax_response error">Error: '+data.errors.friend_email+'</h3>');
        		    //                    };
        		};
        	});
        	
        }
    });
    
    
}

$(document).ready(function() {
    // Browser Detection Object
    var browserD = new Object;
    browserD.safari = $('body').hasClass('safari');
    browserD.firefox = $('body').hasClass('firefox');
    browserD.ie = $('body').hasClass('ie');
    browserD.ffwin = $('body').hasClass('win');
    
    // Send CSRF token in headers with ajax request
    $('html').ajaxSend(function(event, xhr, settings) {
    			    function getCookie(name) {
    			        var cookieValue = null;
    			        if (document.cookie && document.cookie != '') {
    			            var cookies = document.cookie.split(';');
    			            for (var i = 0; i < cookies.length; i++) {
    			                var cookie = jQuery.trim(cookies[i]);
    			                // Does this cookie string begin with the name we want?
    			                if (cookie.substring(0, name.length + 1) == (name + '=')) {
    			                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    			                    break;
    			                }
    			            }
    			        }
    			        return cookieValue;
    			    }
    			    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
    			        // Only send the token to relative URLs i.e. locally.
    			        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    			    }
    			});
    
    // Trip Search Dropdowns
    var trip_select = $('#trip_search_form select');
    trip_select.change(function(){
        var url = $(this).attr('value');
        if (url !== "") {$(window.location).attr('href', url);};
    });
    
    // Print button
	$('.print_action').click(function(){
		window.print();
		return false;
	});
	
	// Bookmark button
	$('.save_action').click(function(){
	    var url = $(this).attr('rel');
	    var title = $('#trip_name').text();
	    title = 'Uncommon Journeys - ' + title;
		
		if (browserD.ie) {
		    // IE
    		window.external.AddFavorite(url, title);
		} else {
		    $('#bookmark_error_dialog').dialog({
    			autoOpen: true,
    			modal: true,
    			resizable: false,
    			width: "400px",
    			open: function(event, ui) {
    			    // Close on overlay click
    			    $('.ui-widget-overlay').click(function(){
    			        $('#bookmark_error_dialog').dialog('close');
    			    });
    			    var message_box = $('#bookmark_error_message');
    			    var message = "";
    			    if (browserD.safari) {
    			        message = "</p>Please press <strong>CMD + D</strong> to bookmark this page.</p>";
    			    } else if (browserD.ffwin){
        			        message = "</p>Please press <strong>CTL + D</strong> to bookmark this page.</p>";
        			} else if (browserD.firefox) {
    			        message = "</p>Please press <strong>CMD + D</strong> to bookmark this page.</p>";
    			    } else {
    			        message = "</p>Please use your browser menu to bookmark this page.</p>";
    			    };
    			    message_box.html(message);
    			} 
			});
		};
		
		
		
		
		return false;
	});
	
	// Mailinglist form (both) ajax and validation
	$(".mailinglist_form").each(function(){
	    $(this).validate({
    	    onfocusout: false,
    	    onkeyup: false,
    	    onclick: false,
    	    focusInvalid: false,
    	    focusCleanup: true,
    	    submitHandler: function(form) { 
    	            form = $(form);
    				var button = form.children('.submit');
    		        button.after('<img class="ajax_loader" src="/static/images/ajax-loader.gif" alt="Loading" />');
    		        var loader = form.children('.ajax_loader');

    		        button.hide(0, function(){
    		            loader.show();
    		        });

    				$('.ajax_response.error').remove();
    				var action = form.attr('action');
    				var form_data = form.serialize();
    				$.post(action, form_data, function(data) {
                         data = $.parseJSON(data);
                         if (data.success) {
                             loader.remove();
                             form.html('<h3 class="ajax_response success">Thank you for signing up</h3>');
                             form.children('h3.ajax_response').fadeIn('slow');
                             					_gaq.push(['_trackEvent', 'Mailinglist', 'Submission']);
                         };
                         if (data.errors) {
                             if (data.errors.email) {
                                 loader.remove();
                                 button.show();
                                 form.append('<label class="ajax_response error">Error: '+data.errors.email+'</label>');
                                 form.children('h3.ajax_response').fadeIn('slow');
                             };
                         };
                     });
    		}
    	});
	});
	
    // HTML5 placeholder text fallback
	// https://github.com/danielstocks/jQuery-Placeholder
	$('input[placeholder], textarea[placeholder]').placeholder();
	
});

// EOF
