﻿var courseResultsXML = basePath+"Search.ashx";

$(document).ready(function() {
$("#courseMap .heading,#courseFormWrapper,#homeIntro .col_695FL").pngFix();
    ApplyIE6MapHack(); /* I know sorry, had to be added to make map bg semi transparent and maintain Image map */
    if ($("#latestPromotions").length > 0) {
        BuildLatestPromoTicker();
    }
    if ($("#map").length > 0) {
        BuildGoogleMap();
    }
    if ($("#imagePager").length > 0) {
        SetupImageGallery();
    }
    if ($(".popup").length > 0) {
        SetupPopups();
    }
    $("fieldset").keypress(function(event) {
        try {
            var target = $("#" + $(this).attr("id")).find("input[type='submit']").attr("id");
            return FireDefaultButton(event, target);
        }
        catch (e) {
        }
    });

    // Set visit Scotland link to be clickable
    $("#widget_button_link").click(function() { return widget_doPopup(); });
});

function BuildLatestPromoTicker(latestPromotions) {

    // Applie the default styles to ensure they don't affect the non-javascript version
    $("#latestPromotions").addClass("javascriptOn");
    
    // If passed in during the recursion set it here
    var latestPromos = latestPromotions
    
    // If not set re-run the search for the panels
    if (!latestPromos)
        latestPromos = $("#latestPromotions li a");
    else {
        
    }

    // Resets the starting position of the links
    latestPromos.css("left", "1000px");

    // This is the number of times we should call the animate function
    var times = latestPromos.length;

    // Animate the first item
    AnimatePromo(latestPromos, 0)

    $(document).everyTime(10500, function(i) {
        // We need an extra time to ensure the last item gets it's full duration so this checks the
        // current index is less than amount of times it should run i.e. the last item
        if (i < times) {
            AnimatePromo(latestPromos, i);
        }
        else {
            // Beacuse we don't call AnimatePromo on the last item we still need to scroll it to the left
            // The because we know it's the last item so we have to start it over again by re-calling the function
            $(latestPromos[i - 1]).animate({ left: "-99999px" }, 11000, function() { BuildLatestPromoTicker(latestPromos); });

        }
    }, times);

    
}

// this slides the link across the promo panel
function AnimatePromo(promoLinks,currentIndex) {
    
    // This is the link we want to animate into place
    var promoLink = promoLinks[currentIndex];

    // If it's not the first item animate the current item out
    if (currentIndex > 0) {
        $(promoLinks[currentIndex - 1]).animate({ left: "-99999px" }, 11000);
    }
    
    // Animate the link we want into place
    $(promoLink).animate({ left: "123px" }, 3000);
}

// does everything required to invoke a new google map
function BuildGoogleMap() {
    
        var coordinates = $("#courseData .coordinates"); // get courses

        if (coordinates.length > 0) {

            initialiseMap("googleMap", "map"); // initialise map ready for plotting the points
            zoomLevel = 6; // set zoom level of the map

            // For each of the courses add a point to the points array
            coordinates.each(function(i) {
                var coordinate = $(this);
                if (i < 200) {

                    points[i] = new mapPoint(coordinate.text(), buildMapPopupHTML(coordinate.parent()));

                }
            });

            plotPoints(); // Plot the points on the map
        }
        else {
            $("#map").empty();
            $("<p/>").text("I'm sorry your search returned 0 courses").appendTo($("#map"));
        }
            

}

// Takes the course in and builds the popup HTML
function buildMapPopupHTML(course) {

    var popupHTML = '<div id="popup" class="fc">';
    popupHTML += course.html();
    popupHTML += '</div>';
    
    return popupHTML;
}

// Setupe the image pager gallery
function SetupImageGallery() {

    /* When required hovers can be created using image rollovers
    $("#imagePager ul a").hover(function() {
        var source = $(this).children("img").attr("src");
        var newSource = source.replace(".png", "_hov.png");
        $(this).children("img").attr("src", newSource)
    },
    function() {
        var source = $(this).children("img").attr("src");
        var newSource = source.replace("_hov.png", ".png");
        $(this).children("img").attr("src", newSource)
    });*/
    // Make an AJAX call to the global variable which holds the refernce to the XML file
    $.ajax({
        type: "GET",
        url: slideShowXmlUrl, // This is a variable added to the courses image pager plugin
        dataType: "xml",
        success: function(xml) {
            // Get the images from the xml
            var imageElements = $("img", xml);
            // Set this element for later checks on whether or not there are images
            imagesLength = imageElements.length;
            
            // This is required to add image gen capabilities
            var imageGenPath = $("#imagePager img.current").attr("src").toLowerCase();
            imageGenPath = imageGenPath.substring(0, imageGenPath.lastIndexOf("&image="));

            // For each of the images add them to the image pager div
            imageElements.each(function(i) {
                var image = $("<img/>");

                // This line will allow for image gen to be used
                image.attr("src", imageGenPath + "&image=" + $(imageElements[i]).attr("src"));

                // If using image gen remove the line below and add the line above
                //image.attr("src", $(imageElements[i]).attr("src"));

                image.attr("alt", $(imageElements[i]).attr("alt"));
                image.attr("index", i); // This is how we know which image to show next
                image.css("display", "none"); // All added elements are set to be removed by default
                image.insertBefore("#imagePager ul"); // Add them before the pager itself
            });

            // Setup the previous and next links
            SetupPreviousNext(0);
        }
    })

}

function SetupPreviousNext(currentIndex) {

    // Set the pager links to set what the current image index is showing
    $("#imagePager ul li a").attr("currentIndex", currentIndex);
    
    // If no images or one image don't show the previous and next;
    if (imagesLength == 0 || imagesLength == 1) {
        $("#imagePager ul").hide();
    }
    else {
        $("#imagePager .next a").click(function() {
            // When clicked, unbind events to ensure multiple clicks are handled
            $("#imagePager ul a").unbind("click");
            // Increment index
            var nextIndex = parseInt($(this).attr("currentIndex")) + 1;
            if (nextIndex > (imagesLength - 1)) { nextIndex = 0; } // if the next index takes us by the range start from 0
            // Show the correct image
            ShowGalleryImage(nextIndex)
            // Now set the new links up
            SetupPreviousNext(nextIndex)
            return false;
        });
        $("#imagePager .previous a").click(function() {
            $("#imagePager ul a").unbind("click");
            var prevIndex = parseInt($(this).attr("currentIndex")) - 1;
            if (prevIndex < 0) { prevIndex = (imagesLength - 1); } // if the next index takes us by the range start from 0
            ShowGalleryImage(prevIndex)
            SetupPreviousNext(prevIndex)
            return false;
        });

    }
}

function ShowGalleryImage(index) {
    if (index <= imagesLength) {
        // Get the current image
        var currentImage = $("#imagePager .current");
        // Set the height of the parent to ensure jumping is avoided
        currentImage.parent().css("height", currentImage.height() + "px");
        
        // Fade out the current image
        currentImage.fadeOut("fast", function() {
            // Remove the current class
            currentImage.removeClass("current");
            // Get the new image
            var newImage = $("#imagePager img[index='" + index + "']");
            newImage.addClass("current"); // set it to be the current
            newImage.fadeIn("fast"); // Fade the new image in
        });
    }
}

function windimension() {

    var windowDimensionArray = new Array();

    if (window.innerHeight !== undefined) {
        windowDimensionArray[0] = window.innerWidth
        windowDimensionArray[1] = window.innerHeight
    }
    else { // IE varieties
        var D = (document.body.clientWidth) ? document.body : document.documentElement;
        windowDimensionArray[0] = D.clientWidth;
        windowDimensionArray[1] = D.clientHeight;
    }
    return windowDimensionArray;
}


function SetupPopups(rel) {
    
    var popupClone = $("div.popup");
    $('<div id="popupOverlay"/>').prependTo($("body"));
    
    //popupClone.appendTo($("body"));
    
    for (var ii = 0; ii < popupClone.length; ii++) {
        var clone = $(popupClone[ii]);
        clone.wrap('<div class="popupContainer"/>');
        
    }

    $("a.popup").click(function() {

        // Setup the overlay
        // var height = $(document).height();
        // var width = $(document).width();

        var diemnsionArray = windimension();

        var width = diemnsionArray[0];
        var height = diemnsionArray[1];        

        $("#homeIntro #courseMap,#homeIntro .transparentPanel").css("opacity", 0.6);
        
        $('#popupOverlay').css({
            opacity: 0.6,
            height: height,
            width: width,
            display: "block"
        })

        var popupId = "#" + $(this).attr("rel");
        return ShowPopup(popupId);


    });

    SetupPopupClose();
}

function ShowPopup(popupId) {
    
    var popup = $(popupId).show(); // The main container
    var height = $(popupId + " .popupContent").height(); // The contents width (Set through CSS)
    var width = $(popupId + " .popupContent").width() + 5; // The contents width (Set through CSS) + 10 is there to generate space for the shadow

    // Animate the container to be the width first then height of the content inside
    popup.animate({ width: width, height: height }, 1200, function() {
    $(popupId + " .popupContent").fadeIn("fast");
    thisMovie('videoPlayer').playPauseVideo();
    });

    return false;
}

function SetupPopupClose() {
    $(".close").click(function() {
        
        thisMovie('videoPlayer').playPauseVideo();
        $("div.popupContent").fadeOut("slow", function() {
        $("div.popup").animate({ height: 0, width: 0 }, 1200, function() { $("#popupOverlay").hide(); $("#homeIntro #courseMap,#homeIntro .transparentPanel").css("opacity", 1); });
        });
        return false;
    });
}

// Will take a fieldset and aslong as it has focus it submits the correct form
function FireDefaultButton(event, target) {

    //event.srcElement doesn't work in FF so we check whether
    //it or event.target exists, using whichever is returned
    var element = event.target || event.srcElement;

    if (event.keyCode == 13 &&
        !(element &&
        element.tagName.toLowerCase() == "textarea")) {
        var defaultButton = document.getElementById(target);

        if (defaultButton && typeof defaultButton.click != "undefined") {
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation) {
                event.stopPropagation();
            }
            return false;
        }
    }
    
    return true;
}

function ApplyIE6MapHack() {
    var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {
	    $("#imageMapWrapper").css("opacity", "0.25");
	}
}