﻿jQuery(document).ready(function(){
       
// DECLARE VARIABLES
        var title = jQuery('h1').html();
        var intro = jQuery('#lblOutput').html();

// DEFINE FUNCTIONS
//
		// Initialize search form
        function initSearchForm(){
            jQuery('#no-js').hide();
            jQuery('form#search').show();
            jQuery('#ddlCountries').val('USA');
            jQuery('#lblCourseList').hide();
            selectCountry();
            getCourses();
        }
       
		// Clear search results and restore introcutory text
        function clearResults(){
            jQuery('h1').html(title);
            jQuery('#lblOutput').html(intro);
            jQuery('#backTop, #backBottom').remove();
            jQuery('#lblOutput').html(intro);
            selectCountry();
        }

		// Hide/Show relevant form elements based on the selected country
		// Ex: If USA or Canada select, show zipcode field
        function selectCountry() {
            country = jQuery('#ddlCountries').val();
            jQuery('form#search .byAddress p > *, form#search .byAddress a').hide();
            jQuery('form#search :disabled').removeAttr('disabled'); 
            jQuery('form#search .byAddress .all-countries, form#search .byAddress .'+country).show();
            jQuery('a#by-zip ~ div').hide();
        }
        
		// Fetch a list of available courses from a .NET web service
        function getCourses() {
            jQuery.ajax({
                type: 'POST',
                url: 'Search.aspx/GetCourseList',
                data: '{}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(msg) {
                    jQuery('#lblCourseList').append(msg);
                }
              });
        }
      
		// Dynamically create contact form
		//
        function buildContactForm(id, name){
                
                // Form submission handler
                function submitForm(v,m,f){
                    var submittedText = '<h2>Thank you.</h2><p>Your message was sent and you will be contacted shortly.</p>';

                    // Send is clicked                   
                    if (v){           
                        jQuery.ajax({
                            type: 'POST',
                            url: 'Search.aspx/ProcessForm',
                            data: JSON.stringify(f),
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            success: function(msg) {
                                response = JSON.parse(msg);
                                jQuery.prompt(response['message'], {buttons: {Close: false}});
                            }
                          });
                    }
                }

                var formBody = '';
                    formBody += '<form id="cf">'
                    formBody += '<h2>Contact ' + name + '</h2>';
                    formBody += '<p><span>Email: </span><input id="cf-email" class="required email" name="email" type="text" /></p>';
                    formBody += '<p><span>First Name: </span><input id="cf-fn" class="required" name="firstName" type="text" /></p>';
                    formBody += '<p><span>Last Name: </span><input id="cf-ln" class="required" name="lastName" type="text" /></p>';
                    formBody += '<p><span>Message: </span><textarea id="cf-msg" class="required" name="comment" cols="30" rows=""></textarea></p>';
                    formBody += '<input id="cf-uid" name="uid" type="hidden" value="' + id + '"/>';
                    formBody += '</form>'
                
                // Show contact form
                var cf = jQuery.prompt(formBody, {submit: submitForm, buttons: { Send: true, Cancel: false }});
                //jQuery('form#cf').validate();
        }
        
		
		// Hide progress bar; show search results; add pagenation, course descriptions, designation descriptions, and contact forms
        function showResults(){
       
            // Set up UI
            jQuery('#loader').hide();
            jQuery('#lblOutput').show();
            jQuery('#lblOutput').prepend('<a id="backTop" href="#">Home</a><div id="pager"></div>');
            jQuery('#lblOutput ul li').quickpaginate({ perpage: 1, showcounter: true, pager: jQuery('#pager') });               
            jQuery('h1').html('Results');
            jQuery('div.contact_form form').hide();
            jQuery('div.courses_taken div.courses').hide();

            // open external links in a new window
            jQuery("#lblOutput a[href^='http://'].practice-url").click(function(){
                var newwindow = window.open(this.href, '_blank');
                    newwindow.focus();
                    return false;
            });


            // Attach handler to "back" links
            jQuery('#backTop').click(function() {
                clearResults();
            });
            
            // Slide out courses
            jQuery('div.courses_taken .course_link').click(function(){
                jQuery(this).siblings('div.courses').slideToggle();
            });
            
            // Attach handler for course descriptions
            jQuery('div.courses_taken div.courses a').click(function(){
                var courseID = jQuery(this).attr('class');
                getCourseDescription(courseID);
            });
            
            // Attach handler for designation descriptions
            jQuery('a.designation').click(function(){
                var designation = jQuery(this).children('img').attr('class');
                getDesignationDescription(designation);
            });
            
            // Attach handler to "contact" links
            jQuery('div.contact_form .contact_link').click(function(){
               var doctorName = jQuery(this).siblings('input[name="doctor-name"][type="hidden"]').val();
               var doctorId = jQuery(this).siblings('input[name="doctor-id"][type="hidden"]').val();
                buildContactForm(doctorId, doctorName);               
            });
            
            // Enable all fields of the search form
            jQuery('form#search :disabled').removeAttr('disabled');
        }
        
        // Use AJAX to fetch course desrciption from a local xml file
        function getCourseDescription(cid){
            jQuery.ajax({
                type: 'GET',
	            url: '../XML/Courses.xml',
	            dataType: 'xml',
	            success: function(xml) {
	                var desc = 'No course description available.';
	                jQuery(xml).find('course').each(function(){
	                    if (jQuery(this).attr('id').toLowerCase() == cid.toLowerCase()){
                            desc = '<h2>' + jQuery(this).find('title').text() + '</h2>';
                            desc += '<p>' + jQuery(this).find('description').text() + '</p>';
	                    }

                    });
                jQuery.prompt(desc);
	            }
            });
        }

        // Use AJAX to fetch designation desrciption from a local xml file
        function getDesignationDescription(designation){
            jQuery.ajax({
                type: 'GET',
	            url: '../XML/Designations.xml',
	            dataType: 'xml',
	            success: function(xml) {
	                var desc = 'No description available.';
	                jQuery(xml).find('designation').each(function(){
	                    if (jQuery(this).attr('name').toLowerCase() == designation.toLowerCase()){
                            desc = '<h2>' + jQuery(this).find('title').text() + '</h2>';
                            desc += '<p>' + jQuery(this).find('description').text() + '</p>';
	                    }

                    });
                jQuery.prompt(desc);
	            }
            });
        }
		
       var searchOptions = { 
            target:  '#lblOutput',
            url:     'Search.aspx', 
            success:  showResults
        }; 
        
        initSearchForm();
        
// BIND EVENT HANDLERS
//
		// Selected country has changed
        jQuery('#ddlCountries').change(selectCountry);
        
		// Hide/Show list of available courses 
        jQuery('span#courseList').click(function(){
            jQuery('#lblCourseList').toggle();
        });
       
       // Toggle Search by City and Search by Zipcode
        jQuery('a#by-city, a#by-zip').click(function(){
            jQuery('a#by-city ~ div, a#by-zip ~ div').slideToggle();
            return (false);
        });

        // Submit search form through AJAX
        jQuery('form#search').ajaxForm(searchOptions);
        
		// Disable empty input fields, Show progress bar when form is submitted
        jQuery('#btnSubmit').click(function(){
            jQuery('#loader').show();
            jQuery('#lblOutput').hide();
        	jQuery('form#search :hidden').each(function (i){
        	    if (jQuery(this).attr('type') != 'hidden'){
        	        jQuery(this).attr('disabled', true); 
        	    }
        	});
        });
        
        
});