jQuery.fn.exists = function () {
    return jQuery(this).length > 0;
}

$(document).ready(function () {
    var primarySlide;
    primarySlide = new HeroSlider(".primary-hero");
    primarySlide.init();

    var gallerySlider;
    gallerySlider = new GallerySlider(".gallery-slide");
    gallerySlider.init();


    initContactCommunityForm();
    var megaNavContent = $("#mega-nav").html();
    $(megaNavContent).appendTo(".main-nav.main");
    initMegaNavs();
    Shadowbox.init();

    if ($("#RegionMapWrapper").exists()) {
        $communityInterface.init();
    }
    if ($("#searchCommunityForm").exists()) {
        initLocationSearchForm();
    }
});

function initLocationSearchForm() {
    $("#searchCommunityFormButton").click(function () {
        if ($("#searchCommunityFormTextbox").val() == '') {
            $("#searchCommunityFormTextbox").addClass("error");
            return false;
        }
        else {
            $("#searchCommunityFormTextbox").removeClass("error");
        }
    });
}

function initContactCommunityForm() {

	var $contactCommunityForm = $("#contactCommunityForm");
	var $communityDropDown = $("#community");
	var $serviceInterestsDropDown = $("#serviceInterests");


	var bindCommunities = function (communityArray) {
		populateDropDown($communityDropDown, communityArray);
	}

	var populateCommunities = function (selectedRegion) {
		$.getJSON("/Sunrise/CommunitiesByRegionJSON", { region: selectedRegion }, function (data) {
			bindCommunities(data);
		});
	}

	var bindServiceInterests = function (serviceInterestArray) {
		populateDropDown($serviceInterestsDropDown, serviceInterestArray);
	};

	var populateServiceInterests = function (community, animate) {
		$.getJSON("/Sunrise/ServiceInterestsByCommunityJSON", { id: community }, function (data) {
			bindServiceInterests(data);
			if (animate)
				$("li.service-of-interest").slideDown();
			else
				$("li.service-of-interest").show();
		});
	};

	var updateServiceInterests = function (animate) {
		var community = $communityDropDown.val();
		populateServiceInterests(community, animate);
		if ($serviceInterestsDropDown.find("option").length == 0)
			$("li.service-of-interest").attr("disabled","disabled");
		else
			$("li.service-of-interest").removeAttr("disabled");
	};

	var updateRegion = function () {
		var region = $("#region").val();
		populateCommunities(region);
		if ($communityDropDown.find("option").length == 0)
			$("li.community").attr("disabled", "disabled");
		else
			$("li.community").removeAttr("disabled");
		updateServiceInterests(false);
	};

	if ($contactCommunityForm.exists()) {
		var defaultSelectedRegion = $("option", $contactCommunityForm).first().val();
		$("#region").change(function () {
			updateRegion();
		});
		updateServiceInterests(false);
	}

	updateServiceInterests(false);
	//updateRegion();

	$communityDropDown.change(function () {
		updateServiceInterests(true);
	});

}

function populateDropDown($element, dataArray) {
	$element.empty();
	$element.append("<option value=\"\">** Please select **</option>");
	for (var i = 0; i < dataArray.length; i++) {
		var item = dataArray[i];
		$element.append("<option value=\"" + item.value + "\">" + item.text + "</option>");
	}
}


function initMegaNavs(){
    $(".main-nav li").hover(function () {
        $(".mega-nav").eq($(this).index()).show(); 
        $(this).find("a").addClass("over");

    }, function () {
        $(".mega-nav").eq($(this).index()).hide();
        $(this).find("a").removeClass("over");
    });
}

function GallerySlider(slideClass) {
    var self = this;
    self.galleryLength = $(slideClass + " ul li").length;
    self.galleryMargin = 15;
    self.galleryCurrent = 0;
    self.init = function () {
        var newWidth = ($(slideClass + " ul li").width() + 15) * self.galleryLength;
        $(slideClass + " ul").width(newWidth);
        if (newWidth > $(slideClass + " .gallery-inner").width()) {
            $(slideClass).append("<div class='btn left'></div><div class='btn right'></div>");
            $(slideClass + " .right").click(function () {
                self.galleryCurrent++;
                self.logic();
                self.moveSlide();
            });
            $(slideClass + " .left").click(function () {
                self.galleryCurrent--;

                self.moveSlide();
            });
        } else {
            $(slideClass + " .gallery-inner").css("margin-left","0px");
        }
        self.moveSlide();
    }
    self.moveSlide = function () {
        self.logic();
        $(slideClass + " ul").animate({
            left: (0 - (($(slideClass + " ul li").width() + 14) * self.galleryCurrent)) + "px"
        }, function () {

        });
    }
    self.logic = function () {
        if (self.galleryCurrent > self.galleryLength - 3) {
            self.galleryCurrent = self.galleryLength - 3;
            $(this).removeClass("active");
        } else {
            $(this).addClass("active");
        }
        if (self.galleryCurrent < 0) {
            self.galleryCurrent = 0;
            $(this).removeClass("active");
        } else {
            $(this).addClass("active");
        }
    }

}

function HeroSlider(slideClass) {
    var self = this;
    self.slideshowLength = $(slideClass + " article").length;
    self.slideshowCurrent = 0;
    self.timeout;
    self.timeDelay = 5000;
    self.init = function () {       
        $(slideClass + " .slide-holder").append('<article>' + $(slideClass + " article:first").html() + '</article>');
        $(slideClass + " article").each(function (i) {
            $(slideClass + " article").eq(i).css({
                position: "absolute",
                left: (755 * i).toString() + "px"
            });
        });
         $(slideClass + " nav li").each(function (i) {
            $(this).append('<span class="marker"></span>');
         });
        $(slideClass + " nav li a").hover(function () {
            self.slideshowCurrent = $(slideClass + " nav li a").index($(this));
            self.moveSlide();
        }, function () {

        });
        self.moveSlide();

    };

    self.timeoutHandler = function () {
        self.slideshowCurrent++;

        self.moveSlide();
    }
    self.moveSlide = function () {
        clearTimeout(self.timeout);
        self.setSelected();
        $(slideClass + " .slide-holder").stop().animate({
            left: [(0 - (755 * self.slideshowCurrent)) + "px", "easeOutQuad"]           
        },{
            duration: 700,
            complete: function () {
                if (self.slideshowCurrent > self.slideshowLength - 1) {
                    $(slideClass + " .slide-holder").css({ left: 0 });
                    self.slideshowCurrent = 0;
                }
                self.timeout = setTimeout(self.timeoutHandler, self.timeDelay);
            }
        });

    }
    self.setSelected = function () {
        var i = (self.slideshowCurrent > self.slideshowLength - 1) ? 0 : self.slideshowCurrent;
        $(slideClass + " nav li").removeClass("selected");
        $(slideClass + " nav li").find(".marker").stop().animate({ right: "0" });
        $(slideClass + " nav li").eq(i).addClass("selected");
        $(slideClass + " nav li").eq(i).find(".marker").stop().delay(250).animate({ right: ["-15px", "easeOutQuad"] });
    }      

}
