/*
* JavaScripts for perfectchoicefunerals.com
*
*
* Date: 2008-12-05
* Author: Steve Taylor
*
* Amended: 2009-05-18
* 1. Merged other jscripts into this one so they fall under the global ns.
* 2. Fixed accordion issue.
*
* Amended: 2009-06-15
* 1. Fixed contact form validation
*
* Amended: 2009-06-17
* 1. Updated Contact Form functions to validate new contact form correctly.
*/
var PerfectChoice = window.PerfectChoice || {};

// Common functions.
PerfectChoice.Common = (function() {
    return {
        handleError: function(msg) {
            alert(msg);
        },
        hideFocus: function() {
            $("a").click(function(e) {
                this.blur();
            });
        },
        textResize: (function() {

            var lastSize;

            function write(name, value, days) {
                var expires = "";
                if (days) {
                    var date = new Date();
                    date.setTime(date.getTime() + (days * 86400000));
                    var expires = "; expires=" + date.toGMTString();
                }
                document.cookie = name + "=" + value + expires + "; path=/";
            };
            function read(name) {
                name += "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
                }
                return null;
            };
            
            return {
                init: function(selector, defaultSize) {
                    // add onclick to aA button and update.
                    lastSize = defaultSize;
                    $(selector).click(function() {
                        write('size', this.className);
                        PerfectChoice.Common.textResize.setTextSize(this.className);
                        return false;
                    });

                    PerfectChoice.Common.textResize.setTextSize(this.className);
                },
                setTextSize: function(defaultSize) {
                    $("body").removeClass(lastSize);
                    lastSize = read('size') || defaultSize;
                    $("body").addClass(lastSize);
                }
            }
        })()
    }
})();

// Search functions.
PerfectChoice.Search = function() {
    var defaultWatermark = "";
    return {
        init: function(elem, watermark) {
            defaultWatermark = watermark;
            $("#" + elem).focus(this.hideWatermark);
            $("#" + elem).blur(this.showWatermark);
        },
        hideWatermark: function(e) {
            if (this.value === defaultWatermark)
                this.value = "";

            this.className = "focus";
        },
        showWatermark: function(e) {
            if (this.value === "") {
                this.value = defaultWatermark;
                this.className = "field";
            }
        }
    }
} ();

// Search functions.
PerfectChoice.SearchResults = function() {
    return {
        init: function() {
            $("select.size").change(function() {
                location.href = $.query.set("PageSize", this.value).set("Page", 1);
            });
        }
    }
} ();

// Functions for the Details page.
PerfectChoice.Details = function() {

    var map, marker, markerText, routeFinder, route, directions;
    var maxZIndex = 1000;

    function initialise(mapElem, routeElem, showWidgets) {

        directions = routeElem;
        map = MMFactory.createViewer(mapElem);
        map.setMapType(MM_WORLD_BEHYBRID);

        // Mouse Behaviour.
        map.setOption("mousewheel:wheelup", "zoomin");
        map.setOption("mousewheel:wheeldown", "zoomout");

        // Widgets.
        if (showWidgets) {
            map.addWidget(new MMMapTypeWidget());
        }

        // Construct the route requester with callback function.
        routeFinder = MMFactory.createRouteRequester(routeLoaded, map);
    }
    function createStepMarker(location, instruction, text, zindex) {
        var marker = map.createMarker(location, { zIndex: zindex, "text": text });
        marker.setInfoBoxContent("<p>" + instruction + "<" + "/p>");
    }
    function showRoute(postcodeStart, postcodeEnd) {
        route = new MMRoute(addLocation(postcodeStart, postcodeEnd));
        routeFinder.request(route);
    }
    function addLocation(postcodeStart, postcodeEnd) {
        var locations = [];

        locations.push(new MMLocation(new MMAddress({ postal_code: postcodeStart, country_code: "GB" })));
        locations.push(new MMLocation(new MMAddress({ postal_code: postcodeEnd, country_code: "GB" })));

        return locations;
    }
    function routeLoaded() {
        if (route.error_code) {
            PerfectChoice.Common.handleError(route.error_code + ": " + route.error_explanation);
        } else {
            // use getAutoScaleLocation to show the entire route on the map, with the route bounds.
            map.goToPosition(map.getAutoScaleLocation(route.bounds));
            displayStages(route);
            // Show the route on the map with PolyLines, by adding each polyline returned.
            for (var i = 0, l = route.polyLine.length; i < l; ++i) {
                map.addOverlay(route.polyLine[i]);
            }
        }
    }
    function displayStages(route) {
        var currentStep = 1;
        var stages = route.stages;
        
        var div = document.createElement("div");
            div.className = "info";

        // The route will be returned in stages. Each stage goes from one specified 'location' to the next:
        for (var count = 0; count < stages.length; count++) {
            // Show some summary information about each stage:
            var stageSummary = "";
            // Show the stage distance, in miles:
            stageSummary += "Driving Distance: <span>" + stages[count].distance.miles + " mile(s)</span>";
            // Show the stage duration, in days, hours and minutes:
            stageSummary += "<br />Estimated Travel Time: <span>";
            if (stages[count].duration.days > 0) { stageSummary += stages[count].duration.days + " day(s) "; }
            if (stages[count].duration.hours > 0) { stageSummary += stages[count].duration.hours + " hour(s) "; }
            if (stages[count].duration.minutes > 0) { stageSummary += stages[count].duration.minutes + " minute(s) "; }
            
            var p = document.createElement("p");
                p.innerHTML = stageSummary;
                p.className = "Summary"
                div.appendChild(p);
                        
            directions.appendChild(div);
            
            var ol = document.createElement("ol");
            ol.id = "stage_" + count;
            ol.className = "directions";
            //ol.start = currentStep;          

            var steps = stages[count].steps;

            // Now we will display each step instruction within this stage:
            for (var stepCount = 0; stepCount < steps.length; stepCount++) {
                // Label the current marker with the step number:
                var text = currentStep;
                // Make the higher numbered step markers appear 'on top of' lower ones:
                var zindex = maxZIndex - currentStep + 1;

                // Use 'A' as marker text if this is the first step of the entire route:
                if (count == 0 && stepCount == 0) {
                    text = "A";
                }
                // Use 'B' as marker text if this is the last step of the entire route:      
                if (count == stages.length - 1 && stepCount == steps.length - 1) {
                    text = "B";
                    zindex = maxZIndex;
                }
                // Create a written 'instruction' using the roadname and/ or roadnumber:
                var instruction = steps[stepCount].instruction;
                var roadname = steps[stepCount].road_name;
                var roadnumber = steps[stepCount].road_number;

                if (roadname && roadnumber) {
                    instruction += " " + roadname + " (" + roadnumber + ") ";
                } else if (roadname) {
                    instruction += " " + roadname + " ";
                } else if (roadnumber) {
                    instruction += " " + roadnumber + " ";
                }

                // Show the distance of this particular step:
                var distance = "";
                if (steps[stepCount].distance.miles > 0) { distance += steps[stepCount].distance.miles + " mile(s) "; }
                if (distance != "") { distance = "" + distance };

                var sp = document.createElement("span");
                    sp.className = "instruction";
                    sp.innerHTML = instruction;
                    
                var sp2 = document.createElement("span");
                    sp2.className = "distance";
                    sp2.innerHTML = distance;
                    
                var li = document.createElement("li");
                    li.appendChild(sp);
                    li.appendChild(sp2);
                    //li.innerHTML = instruction + distance;
                
                ol.appendChild(li);
                
                // Create the step marker, using the instruction and marker text we previously created:
                createStepMarker(steps[stepCount].start_point, instruction, text, zindex);

                ++currentStep;
            }
            directions.appendChild(ol);
            
            
            //add "Back to results" link
            var a = document.createElement("a");
                a.innerHTML = "<< Back to search results";
                a.href = "javascript:history.go(-1)";
            var p = document.createElement("p");
                p.className = "backtoresults";
                p.appendChild(a);
            
            directions.appendChild(p);
        }

        directions.style.display = "block";
        
                
        // Add copyright and disclaimer, as required:
        var copyright = "";
        if (route.copyright) { copyright += "<span>Copyright</span>: " + route.copyright; }
        if (route.disclaimer) {
            copyright += " <span>Disclaimer</span>:  <a href=\"" + route.disclaimer + "\">" 
                      + route.disclaimer + "<" + "/a>"; }

        var p = document.createElement("p");
        p.innerHTML = copyright;
        p.className = "mapviewer_copyright"
        directions.appendChild(p);
    }

    return {
        showMap: function(mapElem, routeElem, postcodeStart, postcodeEnd) {
            // Set map settings.
            initialise(mapElem, routeElem, true);
            // Show map with route and directions.
            showRoute(postcodeStart, postcodeEnd);
        }
    }
} ();

PerfectChoice.UsefulLinks = (function() {
    return {
        init: function() {
            // Add link to header items
            $(".toggle").prev().wrapInner('<a href="#" class="toggleLink"></a>').children().click(function() {
                $(this).parent().next(".toggle").toggle("slow");  // List Items
                $(this).parent().toggleClass("open"); // Heading Tag
                return false;
            }).parent().next(".toggle").hide(); // Hide all by default

            // Show the first one as open.
            $('.toggle.show').show('slow').prev().toggleClass('open');
        }
    }
})();

PerfectChoice.Contact = (function() {
    return {
        init: function(frm, submitButton) {
            $(".form fieldset .info-tooltip").toggleClass("hidden"); // Hide all tooltips

            // Add focus events
            $(".form fieldset input, .form fieldset textarea").focus(function() {
                $(".form .info-tooltip").addClass("hidden");
                $(this).parent().children(".info-tooltip").removeClass("hidden");
                $(".form fieldset").removeClass("active-fieldset");
                $(this).parent("fieldset").addClass("active-fieldset");
            });

            $(".form fieldset .brochure").toggleClass("hide"); // Hide brochure details
            // Toggle event for brochure details
            $(".form fieldset .input-brochure").click(function() {
                $(".form fieldset .brochure").toggleClass("hide");
            });

            $(".form fieldset .something-else").toggleClass("hide"); // Hide 'something else' box
            // Toggle event for 'something else' box
            $(".form fieldset .input-something-else").click(function() {
                $(".form fieldset .something-else").toggleClass("hide");
            });

            $(".form .salutation-other").hide(); //Hide Salutation Other
            //Toggle event for Title:            
            $("#salutation").change(function() {
				if(this[this.selectedIndex].value == 'other')
				{
					$(".form .salutation-other").show();
					$(".form #salutation-other").rules("add", { required: true });
				}
				else
				{
					$(".form .salutation-other").hide();
					$(".form #salutation-other").rules("remove", "required");
				}
				
            });


            //Set default focus on form
            $(".form .focus").focus(); 
			
			
			
			
            // Setup validation for form
            $("#" + frm).validate({
                rules: {
                    fullname: "required",
                    telephone: { required: true, digits: true },
                    email: { required: true, email: true },
                    salutation: { required: true },
                    postaladdress: { required: true },
                    postcode: { required: true, postcode: true },
                    dob: { required: true, date: true },
					burialtype: { required: true }
                },
                messages: {
                    email: "Please enter a valid email address"
                },
                // this will stop any submit button firing the validation
                onsubmit: false
            });

            $.validator.setDefaults({
                debug: false,
                success: "valid"
            });

            $("#" + submitButton).click(function(event) {
                // Manually add the validation to the click event of the button
                PerfectChoice.Contact.validate(frm);
                // If the form is valid then allow to bubble up to the submit.
                if (!$("#" + frm).valid())
                    return false;
            });
        },
        validate: function(frm) {
            // Explicitly validate the form
            $("#" + frm).validate().form()
        }
    }
})();

// Run on all pages on dom ready
$(function() {
    PerfectChoice.Common.hideFocus();
    PerfectChoice.Common.textResize.init(".accessibility-features .text-size a", "textsize-normal");
});

