/// <reference path="jquery-1.4.2.min.js" />
//----------------------------------------------------------------------------------------
//
//    Scripts to make the website do things. Anything you write from scratch goes here
//              REMEMBER TO MINIFY THIS LATER
//
//----------------------------------------------------------------------------------------

/*  Author: Catalyst Studios 
  url: http://catalyststudios.com 
*/





//
// --- place everything inside a contained function to keep scope issues out of play.
//

var scriptWrap = function() {
    var pub = {};

    pub.inProduction = function() {
        // check to see if the site is in production
        // REMEMBER TO CHANGE URL & REMOVE ALERT
        //alert('Change the production url -- Line 27 of /js/script.js');
        return window.location.toString().toLowerCase().indexOf("finalurl.com") > 0;
    }

    // ------------ setup multiple equal height columns ---------------
    pub.equalHeight = function(w, c) {
        var tallest = 0;
        $(w).children(c).each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        $(w).children(c).height(tallest);
    };
    
    //---------------- clinics and providers tab list ----------------------//
    pub.cpTabs = function() {
    var tabNav = $('.providerClinicList .tabs a');
    var tabContainers = $('.providerClinicList div.tabContent > div.tabCol');

    tabNav.click(function() {
      tabContainers.hide().filter(this.hash).fadeIn();
      tabNav.addClass('inactive');
      $(this).removeClass('inactive');
      return false;
    }).filter(':first').click();
  }

    pub.setup = function() {
        // place things in here that need to run on page load

        // set up um header search
        var searchDefault = "Search U of M Web sites";
        var $searchBox = $("#search_field");
        $searchBox.focus(function() {
            if ($searchBox.val() == searchDefault) {
                $searchBox.val("");
            }
        });
        $searchBox.blur(function() {
            if ($searchBox.val() == "") {
                $searchBox.val(searchDefault);
            }
        });

        // main nav drop downs
        function checkHoverRemove(navItem, subNav) {
            if (!navItem.hasClass("hovering") && !subNav.hasClass("hover")) {
                navItem.removeClass("hover");
                subNav.fadeOut("fast");
            }
        };
        //to get all the z-indexes to work these need subnavs need to get pulled out into the body and absolutely positioned.  Plus a bunch of logic to keep the hovering working when you are in a subnav that is no longer in it's old parent
        var subNav = 0;
        $("#mainNav .navItem").hoverIntent(function() {
            var $this = $(this);
            $this.addClass("hover").addClass("hovering");
            if ($this.find(".subNav").size() > 0) {
                var $subNav = $this.find(".subNav").clone();
                $this.find(".subNav").remove();
                $subNav.attr("id", "subNav" + subNav);
                $("body").append($subNav);
                $this.attr("data-subNavId", "#subNav" + subNav);
                subNav++;
                if ($("#container").hasClass("home")) {
                    $subNav.css("top", $this.offset().top + $this.outerHeight());
                }
                else {
                    $subNav.css("top", $this.offset().top + $this.outerHeight() - 10);
                }
                $subNav.css("left", $this.offset().left);
                $subNav.hover(function() {
                    $(this).addClass("hover");
                }, function() {
                    var $newThis = $(this);
                    $newThis.removeClass("hover");
                    setTimeout(function() { checkHoverRemove($this, $newThis); }, 100);
                });
            }
            $($this.attr("data-subNavId")).slideDown('fast');
        }, function() {
            var $this = $(this);
            $this.removeClass("hovering");
            setTimeout(function() { checkHoverRemove($this, $($this.attr("data-subNavId"))); }, 100);
        });

        // create equal height columns with a wrapper of .equalize and cols of .equalHeight
        pub.equalHeight('.equalize', '.equalHeight');

        // set up google maps
        $(".mapThisLocation").click(function(e) {
            e.preventDefault();
            $("#mapsearchpage").modal({ overlayClose: true });
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=scriptWrap.initializeMap";
            document.body.appendChild(script);
        });

        //$("#sideBar a.find").click(function(e) {
        //    e.preventDefault();
        //    searchModal.resetBox(); 
        //    searchModal.filterResults();
        //    $("#searchpageSearch").modal({ overlayClose: true });
        //});

        $("a.findLink").click(function(e) {
            e.preventDefault();
            searchModal.resetBox();
            searchModal.filterResults();
            $("#searchpageSearch").modal({ overlayClose: true });
        });

        searchModal.setupModal("#searchpageSearch"); 
		//searchModal.loadResults((isSSPU? "" : "/UMP") + "/results/searchResults.html");

        // set up recommend friend
        var nameDefault = "Your Name:";
        var $nameBox = $("#recommendName");
        $nameBox.focus(function() {
            if ($nameBox.val() == nameDefault) {
                $nameBox.val("");
            }
        });
        $nameBox.blur(function() {
            if ($nameBox.val() == "") {
                $nameBox.val(nameDefault);
            }
        });

        var emailDefault = "Your E-Mail Address:";
        var $emailBox = $("#recommendEmail");
        $emailBox.focus(function() {
            if ($emailBox.val() == emailDefault) {
                $emailBox.val("");
            }
        });
        $emailBox.blur(function() {
            if ($emailBox.val() == "") {
                $emailBox.val(emailDefault);
            }
        });

        var friendNameDefault = "Friend's Name:";
        var $friendNameBox = $("#recommendFriendName");
        $friendNameBox.focus(function() {
            if ($friendNameBox.val() == friendNameDefault) {
                $friendNameBox.val("");
            }
        });
        $friendNameBox.blur(function() {
            if ($friendNameBox.val() == "") {
                $friendNameBox.val(friendNameDefault);
            }
        });

        var friendEmailDefault = "Friend's E-Mail Address:";
        var $friendEmailBox = $("#recommendFriendEmail");
        $friendEmailBox.focus(function() {
            if ($friendEmailBox.val() == friendEmailDefault) {
                $friendEmailBox.val("");
            }
        });
        $friendEmailBox.blur(function() {
            if ($friendEmailBox.val() == "") {
                $friendEmailBox.val(friendEmailDefault);
            }
        });

        // validate recommend friend
        function blankNameBox() {
            return ($nameBox.val() == "" || $nameBox.val() == "Your Name:");
        }

        function blankFriendNameBox() {
            return ($friendNameBox.val() == "" || $friendNameBox.val() == "Friend's Name:");
        }

        function blankEmailBox() {
            return ($emailBox.val() == "" || $emailBox.val() == "Your E-Mail Address:");
        }

        function isValidEmailBox() {
            return scriptWrap.isValidEmail($emailBox.val());
        }

        function blankFriendEmailBox() {
            return ($friendEmailBox.val() == "" || $friendEmailBox.val() == "Friend's E-Mail Address:");
        }

        function isValidFriendEmailBox() {
            return scriptWrap.isValidEmail($friendEmailBox.val());
        }

        function error(box) {
            box.removeClass("good").addClass("error")
        }

        function success(box) {
            box.removeClass("error").addClass("good");
        }

        $("#recommend .inputs").css("margin-top", $("#recommend").height() / 2 - $("#recommend .inputs").height() / 2);

        $nameBox.change(function() {
            if (blankNameBox()) {
                error($nameBox);
            }
            else {
                success($nameBox);
            }
        });

        $friendNameBox.change(function() {
            if (blankFriendNameBox()) {
                error($friendNameBox);
            }
            else {
                success($friendNameBox);
            }
        });

        $emailBox.change(function() {
            if (blankEmailBox() || !isValidEmailBox()) {
                error($emailBox);
            }
            else {
                success($emailBox);
            }
        });

        $friendEmailBox.change(function() {
            if (blankFriendEmailBox() || !isValidFriendEmailBox()) {
                error($friendEmailBox);
            }
            else {
                success($friendEmailBox);
            }
        });

        $("#recommend .sendButton").click(function() {
            var $errors = $("#recommend .errors");
            if (blankNameBox()) {
                $errors.append("<li>Your name is required.</li>");
            }
            if (blankFriendNameBox()) {
                $errors.append("<li>Your friend's name is required.</li>");
            }
            if (blankEmailBox()) {
                $errors.append("<li>Your E-Mail address is required.</li>");
            }
            else if (!isValidEmailBox()) {
                $errors.append("<li>Your E-Mail address must be valid.</li>");
            }
            if (blankFriendEmailBox()) {
                $errors.append("<li>Your friend's E-Mail address is required.</li>");
            }
            else if (!isValidFriendEmailBox()) {
                $errors.append("<li>Your friend's E-Mail address must be valid.</li>");
            }

            if ($errors.find("li").size() > 0) {
                var $inputs = $("#recommend .inputs");
                var $sendButton = $("#recommend .sendButton");
                var $closeButton = $("#recommend .closeButton");
                $inputs.hide();
                $sendButton.hide();
                $errors.show();
                $closeButton.show();

                $errors.css("margin-top", $("#recommend").height() / 2 - $errors.height() / 2);
                $("#recommend .closeButton").click(function() {
                    $errors.html("");
                    $errors.hide();
                    $closeButton.hide();
                    $inputs.show();
                    $sendButton.show();
                });
            }
        });

        $("#shareTestemonial").click(function() {
            $errors = $("#testemonial .errors");
            $errors.html("");
            var errors = new Array();
            if ($("#fullNameTestemonial").val() == "") {
                errors.push("Your name is required.");
            }
            var $email = $("#emailTestemonial");
            if ($email.val() == "") {
                errors.push("Your e-mail address is required.");
            }
            else if (!scriptWrap.isValidEmail($email.val())) {
                errors.push("Your e-mail must be valid.");
            }
            if ($("#experienceTestemonial").val() == "") {
                errors.push("Your experience is required.");
            }
            if (errors.length > 0) {
                $errors.show()
                for (var i in errors) {
                    $errors.append("<li>" + errors[i] + "</li>");
                }
            }
        });
    }

    pub.isValidEmail = function(string) {
        return string.search(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/) != -1;
    };


    pub.initializeMap = function() {
	var clinicLatitude = document.getElementById("clinicLatitude").innerHTML;
	var clinicLongitude = document.getElementById("clinicLongitude").innerHTML;
	var clinicTitle = document.getElementById("clinicTitle").innerHTML;
        var myLatlng = new google.maps.LatLng(clinicLatitude, clinicLongitude);
        var mapOptions = {
            zoom: 16,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        var map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
        var markerOptions = new Array(
            {
                map: map,
                title: clinicTitle,
                position: new google.maps.LatLng(clinicLatitude, clinicLongitude),
                icon: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
            }
        );
        for (i = 0; i < markerOptions.length; i++) {
            var marker = new google.maps.Marker(markerOptions[i]);
        }
    }

    return pub;
} ();









//
// --- jQuery document ready fires when page is loaded. (but not necessarily when you want to; hence the ahc.Common.onReady)
//
ahc.Common.onReady(function() {
  scriptWrap.setup(); // call setup function above
  $("a:external").attr("target", "_blank"); // check if a link is external to this site and open it in a new winow
  scriptWrap.cpTabs();
});


// --- Regular expression to check target location of a link

$.expr[':'].external = function(obj){
    return 	obj.href.indexOf("mailto:") != 0 &&
    		obj.href.indexOf("javascript:") != 0 &&
    		(obj.hostname != location.hostname);
};

// --- create equal height objects
jQuery.fn.equalHeight = function() {
  var maxHeight = 0;
  this.each(function() {
    $(this).height('auto');
    if ($(this).height() > maxHeight) {
      maxHeight = $(this).height();
    }
  });
  this.height(maxHeight);
};

