jQuery(document).ready(function () {
    // Menu Hover Behavior
    jQuery("li.menuItem").mouseenter(function () {
        // Make sure there is no permanent on state
        if (!jQuery(this).hasClass("permOn")) {
            // Add the on state
            jQuery(this).addClass("on");

            if (this.id == "Painting_Professionals") {
                jQuery("#nav_painting_professionals").css("display", "block");
                jQuery("#nav_house_painting").css("display", "none");
            }
            else if (this.id == "House_Painting") {
                jQuery("#nav_painting_professionals").css("display", "none");
                jQuery("#nav_house_painting").css("display", "block");
            }
        }
    }).mouseleave(function () {
        // Make sure there is no permanent on state
        if (!jQuery(this).hasClass("permOn")) {
            // Remove the on state
            jQuery(this).removeClass("on");

            if (this.id == "Painting_Professionals") {
                window.setTimeout(function () {
                    jQuery("#nav_painting_professionals").css("display", "none")
                }, 1500);
            }
            else if (this.id == "House_Painting") {
                window.setTimeout(function () {
                    jQuery("#nav_house_painting").css("display", "none")
                }, 1500);
            }
        }
    });

    // Override the AJAX transport method for fixing IE crossdomain AJAX issues.
    jQuery.ajaxTransport("+*", function (options, originalOptions, jqXHR) {
        if (jQuery.browser.msie && window.XDomainRequest) {
            var xdr;

            return {
                send: function (headers, completeCallback) {
                    xdr = new XDomainRequest();
                    xdr.open("get", options.url);

                    xdr.onload = function () {
                        if (this.contentType.match(/\/xml/)) {
                            var dom = new ActiveXObject("Microsoft.XMLDOM");
                            dom.async = false;
                            dom.loadXML(this.responseText);
                            completeCallback(200, "success", [dom]);
                        }
                        else {
                            completeCallback(200, "success", [this.responseText]);
                        }
                    };

                    xdr.ontimeout = function () {
                        completeCallback(408, "error", ["The request timed out."]);
                    };

                    xdr.onerror = function () {
                        completeCallback(404, "error", ["The requested resource could not be found."]);
                    };

                    xdr.send();
                },
                abort: function () {
                    if (xdr) {
                        xdr.abort();
                    }
                }
            };
        }
    });

    // Check if there's a carousel
    if (jQuery("div#gallery").length > 0) {
        // Check if the photo set URL ends with a trailing slash
        if (jQuery("input[name=photoSetURL]").val().substr((jQuery("input[name=photoSetURL]").val().length - 1), 1) == "/") {
            // Remove the slash
            jQuery("input[name=photoSetURL]").val(jQuery("input[name=photoSetURL]").val().substr(0, (jQuery("input[name=photoSetURL]").val().length - 1)));
        }

        // Get the set data
        jQuery.ajax(
		{
		    type: "GET",
		    url: "http://api.flickr.com/services/rest",
		    data:
			{
			    method: "flickr.photosets.getPhotos",
			    api_key: "93a8b0c04deb6cb2c729dd82447373d9",
			    photoset_id: jQuery("input[name=photoSetURL]").val().split("/")[jQuery("input[name=photoSetURL]").val().split("/").length - 1],
			    extras: "url_m,url_o",
			    format: "json",
			    nojsoncallback: "1"
			},
		    mimeType: "application/json",
		    dataType: "json",
		    crossDomain: true,
		    success: function (data, textStatus) {
		        // Declare the photo markup string
		        var photoMarkup = new String();

		        // Set up index
		        var photoIndex = 0;

		        // Set up height array
		        var photoHeights = [];

		        // Loop through the data and build the carousel
		        for (var i in data.photoset.photo) {
		            // Make sure this index is defined
		            if (data.photoset.photo[i].url_m != undefined) {
		                // Add the markup
		                photoMarkup += "<div class=\"galleryPic\">";
		                photoMarkup += "<img src=\"" + data.photoset.photo[i].url_m + "\" width=\"305\" />";
		                photoMarkup += "<p class=\"galleryCaption\">" + data.photoset.photo[i].title + "</p>";
		                photoMarkup += "</div>";
		            }
		        }

		        // Populate the carousel
		        jQuery("div.galleryContent").html(photoMarkup);

		        // Cycle through the gallery pics
		        jQuery("div#gallery").children("div.galleryContent").children("div.galleryPic").each(function () {
		            // Stagger each photo
		            jQuery(this).css({ left: String((parseInt(jQuery(this).index()) * 310) + 5) + "px" });
		        });

		        // Set the loaded count
		        var loaded = 0;

		        // Loading listener for the first two images in the gallery
		        jQuery("div.galleryPic:eq(0) img, div.galleryPic:eq(1) img").load(function () {
		            // Increment the loaded variable
		            loaded++;
		        });

		        // Set the interval
		        var loadedInterval = setInterval(function () {
		            if (loaded == 2) {
		                // Capture the image heights
		                firstImageHeight = jQuery("div.galleryPic:eq(0) img").height();
		                secondImageHeight = jQuery("div.galleryPic:eq(1) img").height();

		                // Hide the loading graphic
		                jQuery("div.galleryLoading").hide();

		                // Determine the greater height
		                if (firstImageHeight > secondImageHeight) {
		                    // Set the height
		                    jQuery("div#gallery").css({ height: firstImageHeight + "px" });
		                }
		                else {
		                    // Set the height
		                    jQuery("div#gallery").css({ height: secondImageHeight + "px" });
		                }

		                // Show the gallery
		                jQuery("div.galleryContent").show();

		                // Clear the interval
		                clearInterval(loadedInterval);
		            }
		        }, 10);
		    }
		});
    }

    // Carousel navigation handler
    jQuery("div.galleryControls div img").click(function () {
        // Get the type of button clicked
        var action = jQuery(this).parent("div").attr("class");

        // Determine action
        switch (action) {
            case "controlLeft":
                // Check if we're at the end of the carousel
                if (parseInt(jQuery("div.galleryPic").first().css("left")) !== 5) {
                    // Move the images forward
                    jQuery("div.galleryPic").each(function () {
                        jQuery(this).css("left", (parseInt(jQuery(this).css("left")) + 310) + "px");
                    });
                }
                break;

            case "controlRight":
                // Check if we're at the end of the carousel
                if (parseInt(jQuery("div.galleryPic").last().css("left")) !== 315) {
                    // Move the images forward
                    jQuery("div.galleryPic").each(function () {
                        jQuery(this).css("left", (parseInt(jQuery(this).css("left")) - 310) + "px");
                    });
                }
                break;
        }

        // Cycle through the gallery controls
        jQuery("div.galleryPic").each(function () {
            // Determine if this one is currently in view in the carousel
            if (parseInt(jQuery(this).css("left")) === 5) {
                // Record the index
                inViewIndex = jQuery(this).index();
            }
        });

        // Determine which of the starting two images is the tallest
        var imageFirstHeight = jQuery("div.galleryPic").eq(inViewIndex).height() + 5;
        var imageSecondHeight = jQuery("div.galleryPic").eq(inViewIndex + 1).height() + 5;

        // Determine the greater height
        if (imageFirstHeight > imageSecondHeight) {
            // Set the height
            jQuery("div#gallery").css({ height: imageFirstHeight + "px" });
        }
        else {
            // Set the height
            jQuery("div#gallery").css({ height: imageSecondHeight + "px" });
        }
    });

    // Check if there is a home carousel
    if (jQuery("div#holder").length > 0) {
        // Set needed variables
        var currentSlide = 0;
        var totalSlides = parseInt(jQuery("div#holder").children("div").length) - 1;

        // Set an interval for the slides
        setInterval(function () {
            // Figure out how to increment the slide count
            if (currentSlide == totalSlides) {
                // Reset currentSlide to zero
                currentSlide = 0;
            }
            else {
                // Increment the current slide
                currentSlide++;
            }

            // Fade out all of the slides
            jQuery("div#holder").children("div").animate({ opacity: 0.0 }, { queue: false, duration: 500 });

            // Fade in the current slide
            jQuery("div#holder").children("div").eq(currentSlide).animate({ opacity: 1.0 }, { queue: false, duration: 500 });
        }, 5000);
    }

    if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) < 7) {
        jQuery(".pops").removeClass("pops");
    }

    jQuery(".pops").colorbox(
	{
	    width: "1070px",
	    height: "880px",
	    iframe: true,
	    speed: 250
	});

    jQuery(".citiesPops").colorbox(
	{
	    innerWidth: 0,
	    innerHeight: 0,
	    width: "605px",
	    height: "420px",
	    iframe: true,
	    scrolling: false,
	    speed: 250
	});
});

/*** Begin Utility Functions ***/

function ValidateTextBox(source, args) {
    var cntrl_id = jQuery(source).attr("controltovalidate");
    var cntrl = jQuery("#" + cntrl_id);
    var is_valid = $(cntrl).val() != "";
    is_valid ? $(cntrl).removeClass("error") : $(cntrl).addClass("error");
    is_valid ? $('#spnValidationError').hide() : $('#spnValidationError').show();
    args.IsValid = is_valid;
}

/*** End Utility Functions ***/
