/* Utility.js */
	
	/* Variables ------------------------------------------------------------------------------------------- */
	var xmlHttp;
	var current_page = "";
	var myMap;
    var myPano;
    var myDirections;
    var cars_location;
    var geocoder = new GClientGeocoder();
    var car_obj;
	
	/* Functions ------------------------------------------------------------------------------------------- */
	
	/* Site Functions ------------------------ */
	
	/* Highlight Navigation Icon */
    function highlightNavigationPage() {
    
       try {
       
           var str = document.title.toString();
           var field = "";
           
           if (str.search(/home/i) != -1) {
               field = "nav-home";
               
           } else if (str.search(/about/i) != -1) {
               field = "nav-about";
           
           } else if (str.search(/inventory/i) != -1) {
                field = "nav-inventory";
           
           } else if (str.search(/services/i) != -1) {
               field = "nav-services";
           
           } else if (str.search(/location/i) != -1) {
               field = "nav-location";
           
           } else if (str.search(/contact/i) != -1) {
               field = "nav-contacts";
           
           }
           
           if (field.length) {
                document.getElementById(field).style.backgroundPosition = "0px -43px";
                document.getElementById(field).onclick = function() { return false; };
           }
           
           current_page = field;
           
        } catch (e) {
           alert(e.message);
           return false;
       }
       
       return true;
    }
    
    function GetXmlDocObject() {
        var xmlDocObj = null;
        
        try {
             /* Internet Explorer */
             xmlDocObj = new ActiveXObject("Microsoft.XMLDOM");
         
        } catch (e) {
        
            try {
               /* Firefox, Opera 8.0+, Safari */
                xmlDocObj = document.implementation.createDocument("", "", null);
                
            } catch (e) {
                alert(e);
                return;
            }
        }
        
        xmlDocObj.async = false;
        return xmlDocObj;
    }
    
    /* Vehicle Page Object */
    function Vehicle() {
  
	    /* Private Variables */
	    var _images = new Array();
	    var _year;
	    var _make;
	    var _model;
	    var _colors;
	    var _descrp;
	    var _show_running = true;
        var _show_img = 1;
	    
	    /* Set Attributes of the Vehicle */
	    this.setAttributes = function(a_year, a_make, a_model, a_colors, a_descrp) {
	    
	        try {
	            _year = a_year;
	            _make = a_make;
	            _model = a_model;
	            _colors = a_colors;
	            _descrp = a_descrp;
	            
	        } catch(exception) {
	            alert(exception);
	            return false;
	        }
	        return true;
	    }
	    
	    /* Debugging Alert of Attributes */
	    this.getAttributes = function() {
	        alert("YEAR - " + _year + " Make - " + _make + " Model - " + _model + " Color - " + _colors + " Descrp - " + _descrp);
	    
	    }
	       
	    /* Add Image */    
	    this.addImage = function(a_main, a_thmb) {
	    
	       //alert("ADDING - Main : " + a_main + ", Thumbnail : " + a_thmb);
	        try {
	              var next_id = this.getNumberOfImages();
	              var new_image = {
	                   id: next_id,
	                   main_image: a_main,
	                   thumb_image: a_thmb
	              };
	              
	              _images.push(new_image);
	              
	        } catch(exception) {
	           alert(exception);
	           return false;
	        }
	        return true;
	    } 
	    
	    /* Number of Images in Array */
	    this.getNumberOfImages = function() {
	          return _images.length;
	    } 
	    
	    /* Return Image Object in Array */
	    this.getImageObject = function(id) {
	        return _images[id];
	    }
	    
	    /* Return Year */
        this.getYear = function() {
            return _year;
        }
         
        /* Return Make */
        this.getMake = function() {
            return _make;
        }
        
        /* Return Model */
        this.getModel = function() {
            return _model;
        }
        
        /* Return Colors */
        this.getColors = function() {
            return _colors;
        }
        
        /* Return Description */
        this.getDescription = function() {
            return _descrp;
        }
        
        /* Return Run SlideShow */
        this.getShowRunning = function() {
            return _show_running;
        }
        
        /* Return SlideShow Current Image */
        this.getShowImage = function() {
            return _show_img;
        }
        
        /* Set Run SlideShow */
        this.setShowRunning = function(a_status) {
            _show_running = a_status;
        }
        
        /* Set SlideShow Current Image */
        this.setShowImage = function(a_img) {
            _show_img = a_img;
        }
        
    } /* END - Vehicle Page Object */
    
    function loadDOTMCar() {
    
        try {
	        xmlHttp = GetXmlDocObject();
	        
	        if (xmlHttp == null) {
	             alert("Your Browser does not support our HTTP XML Request!");
	             return false;
	        }
	    
	        xmlHttp.load("xml/dotm.xml");
	        
	        /* New Vehicle */
	        car_obj = new Vehicle();
	        
	        /* Add Images */
            var image_nodes = xmlHttp.getElementsByTagName("image");
            if (image_nodes.length < 3) {
               throw ("Not Enough Images for Deal of the Month Showcase!");
            }
           
            var image_main;
            var image_thmb;
            for (var i = 0; i < image_nodes.length; i++) {
                image_main = xmlHttp.getElementsByTagName("main")[i].childNodes[0].nodeValue;
                image_thmb = xmlHttp.getElementsByTagName("thumbnail")[i].childNodes[0].nodeValue;
               
                car_obj.addImage(image_main, image_thmb);
            }
	        	                
	        /* Add Attributes */
	        car_obj.setAttributes(
	           xmlHttp.getElementsByTagName("year")[0].childNodes[0].nodeValue,
	           xmlHttp.getElementsByTagName("make")[0].childNodes[0].nodeValue,
	           xmlHttp.getElementsByTagName("model")[0].childNodes[0].nodeValue,
	           xmlHttp.getElementsByTagName("color")[0].childNodes[0].nodeValue,
	           xmlHttp.getElementsByTagName("description")[0].childNodes[0].nodeValue
	           ); 
	        
	        /* DEBUG */   
	        //car_obj.getAttributes();
            	  
            /* Set Showcase Main */	       
            document.getElementById("DOTM-main-1").src = car_obj.getImageObject(0).main_image;
            document.getElementById("DOTM-main-2").src = car_obj.getImageObject(1).main_image;
            
            /* Set Thumbs */
	        document.getElementById("DOTM-thmb-1").src = car_obj.getImageObject(0).thumb_image;
	        document.getElementById("DOTM-thmb-2").src = car_obj.getImageObject(1).thumb_image;
	        document.getElementById("DOTM-thmb-3").src = car_obj.getImageObject(2).thumb_image;
	        
	        /* Set Text Content */
	        document.getElementById("DOTM-year").innerHTML = car_obj.getYear();
	        document.getElementById("DOTM-make").innerHTML = car_obj.getMake();
	        document.getElementById("DOTM-model").innerHTML = car_obj.getModel();
	        document.getElementById("DOTM-colors").innerHTML = car_obj.getColors();
	        document.getElementById("DOTM-description").innerHTML = car_obj.getDescription();
	        
	        setTimeout(function(){startSlideShow("DOTM-main-1", "DOTM-main-2"); parameter = null}, 4000);
	        
	    } catch(exception) {
	       alert(exception);
	       return false;
	    }
        return true;
    }
     
    /* Switch Image Based on Containing Div's ID */
    function userSwitchSlideImage(id, div1, div2) {
    
        try {
    
	        /* Stop Slideshow */
	        car_obj.setShowRunning(false);
	        document.getElementById(div2).style.display = "none";
	    
	        var id_value = id.substring(id.length-1);
	        var image_id = (id_value - 1); 
	        
	        if (id_value == car_obj.getShowImage()) {
	            return false;
	        } 
	        else {
	            car_obj.setShowImage(id_value);
	        }
	
	        dojo.fadeOut({ node: div1, duration: 500, onEnd: 
	            function() { 
			        document.getElementById(div1).src = car_obj.getImageObject(image_id).main_image;
	                dojo.fadeIn({ node: div1, duration: 1000}).play();
	            }
	        }).play(); 
        } catch(exception) {
            alert(exception);
            return false;
        }
        return true;
    }
   
    /* Slideshow with Car */
    function startSlideShow(div1, div2) {
        try {
        
	        if (car_obj.getShowRunning()) {
	        
	            if (car_obj.getShowImage() > (car_obj.getNumberOfImages() - 1)) {
	                car_obj.setShowImage(0);
	            }
	            
	            document.getElementById(div2).src = car_obj.getImageObject(car_obj.getShowImage()).main_image;
	            dojo.fadeOut({ node: div1, duration: 1000,
	                onEnd: function() { 
	                    document.getElementById(div1).src = document.getElementById(div2).src;
	                    dojo.fadeIn({ node: div1, duration: 1000}).play();
	                    car_obj.setShowImage((car_obj.getShowImage() + 1));
	                }
	             }).play();
	             
	             setTimeout(function(){startSlideShow(div1, div2); parameter = null}, 4000);
	        }
	        
        } catch(exception) {
            alert(exception);
            return false;
        }
        return true;
    }
	
	/* Location Functions ------------------------- */
	
	/* Send Direction Help Box Request to Google Maps */
	function getDirections() {
	   
	   try {
	
		   var user_addr = "";
		   
		   var address = document.getElementById("getAddr").value;
		   if ((address != "") && (address != "Enter your Address")) {
		       user_addr += address + ", ";
		   }
		   
		   var city = document.getElementById("getCity").value;
	       if ((city != "") && (city != "Enter your City")) {
	           user_addr += city + ", ";
	       }
	       
		   user_addr += document.getElementById("getState").value;
		   
		   var zip = document.getElementById("getZip").value;
	       if ((zip != "") && (zip!= "Zip")) {
	           user_addr += ", " + zip;
	       }
	       
	       geocoder.getLatLng(user_addr, function(point) {
		      if (!point) {
	               alert(user_addr + " not found");
	          } else {
	               user_addr = point.toUrlValue();
	                    
	               if (current_page != "nav-location") {
	                  window.location = "http://www.carsareuspa.com/location.php?user_addr=" + user_addr;
	               }
	          }
	       });
		 
	   } catch (e) {
	       alert(e.message);
	       return false;
	   }
	   
	   return true;
	}
	
	/* Clear Get Directions Help Box Input Field */
	function clearDirectionsInput(id) {
	
	   try {
	   
	       document.getElementById(id).value = "";
	       document.getElementById(id).style.color = "#000000";
	       
	   } catch (e) {
           alert(e.message);
           return false;
       }
       
       return true;
	}
	
	/* Get Embedded Maps from Google */
     function getMaps(user_location) {
     
        try {
          
            if (GBrowserIsCompatible()) {
                
                myMap = new GMap2(document.getElementById("map_canvas"));
                myPano = new GStreetviewPanorama(document.getElementById("street_view_canvas"));    
                myDirections = new GDirections(myMap, document.getElementById("route_mapping"));
                
                var myPOV = { yaw:40, pitch:0 };
                cars_location = new GLatLng(41.492218,-75.698032);
                
                myMap.setCenter(cars_location, 10);
                myMap.setUIToDefault();
                
                GEvent.addListener(myPano, "error", handleNoFlash);
                myPano.setLocationAndPOV(cars_location, myPOV);
                
                var marker = new GMarker(cars_location);
                myMap.addOverlay(marker);
                
                var info_html = "<div style=\"width: 240px;\"><img src=\"images/cars_map_icon.gif\" style=\"float: right\"/>";
                info_html += "<b style=\"font-size: 12pt;\">Cars Are Us</b><br/>";
                info_html += "701 South State Street<br/>";
                info_html += "Clarks Summit, PA 18411<br/>";
                info_html += "1 (800) 586-7177<br/><br/>";
                info_html += "<i>http://www.carsareuspa.com</i></div>";
                
                myMap.openInfoWindow(cars_location, info_html);

                GEvent.addListener(marker, "click", function() {
                    myMap.openInfoWindow(cars_location, info_html);
                });
          
                GEvent.addListener(marker, "dblclick", function() {
                    myMap.setMapType(G_SATELLITE_MAP);
                    myMap.setCenter(cars_location, 18);
                });                           
    
                        
                if (user_location.length > 0) {
                    showDirections(user_location);
                }
                       
            } else {
                document.getElementById("map-content").style.display = "none";
                document.getElementById("map-error").style.display = "";
                document.getElementById("get-location-button").onclick = function() { return false; };
                      
            }
                      
        } catch (e) {
            alert(e.message);
            return false;
        }
        
        return true;
     }                

    /* Show Directions */
    function showDirections(address) {
        
        try {
            
            var user_addr = "";
        
            if (address == null || address.length <= 0) {
                        
                var address = document.getElementById("location_addr").value;
                if ((address != "") && (address != "Enter your Address")) {
                    user_addr += address + ", ";
                }
                
                var city = document.getElementById("location_city").value;
                if ((city != "") && (city != "Enter your City")) {
                    user_addr += city + ", ";
                }
                
                user_addr += document.getElementById("location_state").value;
                
                var zip = document.getElementById("location_zip").value;
                if ((zip != "") && (zip!= "Zip")) {
                    user_addr += ", " + zip;
                }
                               
                document.getElementById("user_mapping").innerHTML = "FROM: " + user_addr;

            } else {
                /* Address Input from Home Page */
                user_addr = address;
            }
            
            geocoder.getLatLng(user_addr, function(point) {
                if (!point) {
                    alert(user_addr + " not found");
                } else {
                    myMap.setMapType(G_NORMAL_MAP);
                    myMap.setCenter(point, 11);
                    var marker = new GMarker(point);
                    myMap.addOverlay(marker);          
                    myMap.openInfoWindow(point, document.createTextNode("Your Location"));                        
                    myDirections.clear();
                    myDirections.load("from: " + point.toUrlValue() + " to: "+ cars_location.toUrlValue());
                            
                 }
            });
            
            window.location.hash="directions";
            document.getElementById("directions-route").style.display="block"; 
                      
        } catch (e) {
            alert(e.message);
            return false;
        }
    }
    
    /* Street View Error Handling */
    function handleNoFlash(errorCode) {
       if (errorCode == 603) {
           document.getElementById("street_view_canvas").style.display = "none";
           alert("Error: Flash doesn't appear to be supported by your browser");
           return;
       }
    }
    
	/* Contacts Functions ------------------------ */
	
    /* Clear Contact Form Input Field */
    function clearFormInput(id) {
    
       try {
       
           var str = document.getElementById(id).value;

           if (str.search(/Enter your/) != -1) {
                clearDirectionsInput(id);
           }
           
       } catch (e) {
           alert(e.message);
           return false;
       }
       
       return true;
    }

    /* Obtain the Browser Specific XMLHTTP Object */
    function GetXmlHttpObject() {
        var xmlHttp = null;
        
        try {
             /* Firefox, Opera 8.0+, Safari */
             xmlHttp = new XMLHttpRequest();
         
        } catch (e) {
            /* Internet Explorer */
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                
            } catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }
        
    /* Form Rollover Color Change Function */
    function formOver(frm_name) {
        document.getElementById(frm_name).style.borderColor = "#1733f3";
        document.getElementById(frm_name).style.color = "#000000";
    }
            
    /* Form Rollout Color Change Function */
    function formOut(frm_name) {
        document.getElementById(frm_name).style.borderColor = "#000000";
    }
    
    /* Validate Contact Form */        
    function validateContactForm() {
    
        try {
            var err_message = "";
            var email_regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            
            var name = document.getElementById("contact-name").value;
            if ((name.search(/Enter your/) != -1) || (name.length <= 0)) {
                err_message += " - Your Name is required\n";
            }
            
            var email = document.getElementById("contact-email").value;
            if ((email.search(/Enter your/) != -1) || (email.length <= 0)) {
                err_message += " - Your E-Mail Address is required\n";
                
            } else if (email.length > 0) {
                if (!email_regex.test(email)) {
                    err_message += " - Invalid E-Mail Account\n";
                }
            }
            
            var phone = document.getElementById("contact-phone").value;
            if ((phone.search(/Enter your/) != -1) || (phone.length <= 0)) {
                document.getElementById("contact-phone").value = "";
            }
            
            var message = document.getElementById("contact-message").value;
            if ((message.search(/Enter your/) != -1) || (message.length <= 0)) {
                document.getElementById("contact-message").value = "";
                err_message += " - Your Message is empty\n";
                
            }
    
            /* Display Error Messages */
            if (err_message.length > 0) {
                alert("Contact Form Error(s)\n Please fix the following before sending:\n" + 
                      "------------------------------------\n" + err_message);
                return false;
            }
            
        } catch (exception) {
             alert(exception);
             return false;
        }
        
        return true;
    }
            
    /* Send Web Form Email */        
    function sendFormEmail() {
    
        if (!validateContactForm()) {
            return false;
        }
    
        xmlHttp = GetXmlHttpObject();
        if (xmlHttp == null) {
             alert("Your Browser does not support our HTTP Email Request!");
             return false;
        }
        
        var name = document.getElementById("contact-name").value;
        var email = document.getElementById("contact-email").value;
        var phone = document.getElementById("contact-phone").value;
        var message = document.getElementById("contact-message").value;
        
        var subject = "Cars Are Us Website Contact from " + name;
        var url = "src/contact_mail.php";
        url += "?name=" + name;
        url += "&email=" + email;
        url += "&phone=" + phone;
        url += "&message=" + message;
        url += "&subject=" + subject;
        url += "&action=send";
        
        /* Disable Form Fields and Buttons */
        document.getElementById("contact-name").disabled = true;
        document.getElementById("contact-email").disabled = true;
        document.getElementById("contact-phone").disabled = true;
        document.getElementById("contact-message").disabled = true;
        
        document.getElementById("contact-send").onclick = function() { return false; };
        document.getElementById("contact-clear").onclick = function() { return false; };
        document.getElementById("contact-form-response").innerHTML = "Sending Message... Please Wait... ";
        document.getElementById("contact-loader-img").style.display = "block";
                    
        xmlHttp.open("GET", url);
        xmlHttp.onreadystatechange = handleEmailResponse;
        xmlHttp.send(null);
    }
            
    /* Display Feedback to User's Contact Form after successful Call */
    function handleEmailResponse() {
        if (xmlHttp.readyState == 4) {
            document.getElementById("contact-loader-img").style.display = "none";
            document.getElementById("contact-form-response").innerHTML = xmlHttp.responseText;
        }
    }
       
    /* Reset Placeholders and Form */        
    function resetContactForm() {
        document.getElementById("contact-name").value = "";
        document.getElementById("contact-email").value = "";
        document.getElementById("contact-phone").value = "";
        document.getElementById("contact-message").value = "";
      
        return true;
    }