/* -------------------------------------------------------------------

 Boondoggle - Hans Dreesen
 Rabobank Nederland

 This JavaScript file collects all general functions used
 throughout the site, as well as some smaller specific
 functions.

 ------------------------------------------------------------------- */



// DEFINE VARS AND FUNCTIONS FOR FLASH HEADER ON SEARCH PAGES
var flashvars = {};
var params = {};
var attributes = {};
var expanded = false;
var expandHeight = 210;
var homePage = false;

function swfPause() {
    if (expanded) document.flashContent.eb_pause(true);
}
function swfPlay() {
    if (expanded) document.flashContent.eb_play(true);
}

function eb_expandFromFlash() {
    if (!expanded) {
        $("#jobBlock").animate({"marginTop": "+=" + expandHeight + "px"}, 200);
        if (homePage) {
            $("#flashContent").animate({"marginBottom": "+=" + expandHeight + "px"});
        } else {
            document.flashContent.eb_expand();
        }
        expanded = true;
    }
}

function collapse() {
    if (expanded) {
        $("#jobBlock").animate({"marginTop": "-=" + expandHeight + "px"}, 200);
        if (homePage) {
            $("#flashContent").animate({"marginBottom": "-=" + expandHeight + "px"});
        } else {
            document.flashContent.eb_colaps();
        }
        swfPause();
        expanded = false;
    }
}

function getBaselocationUrl() {

    var baselocationUrl;

    if (document.baseURI === undefined) {
        var baseElements = document.getElementsByTagName("base");
        if (baseElements.length > 0) {
            baselocationUrl = baseElements[0].href;
        } else {
            baselocationUrl = "";
        }
    }
    else {
        baselocationUrl = document.baseURI;
    }

    if (baselocationUrl.charAt(baselocationUrl.length - 1) == '/') {
        if (baselocationUrl.length == 1) {
            baselocationUrl = "";
        } else {
            baselocationUrl = baselocationUrl.substring(0, baselocationUrl.length - 1);
        }
    }

    return baselocationUrl;
}

function initializeAjaxPaging() {
    // Attach to all page links
    $(".searchResultInfo .pager a").click(pressPagerLink);
}

function pressPagerLink(event) {
    // Get target
    targetUrl = event.target;

    // Perform ajax call
    $("#searchColLeft").load(targetUrl + " #searchColLeft > *", null, processAjaxResponse);

    // Stop propagation
    event.stopImmediatePropagation();

    return false;
}

function processAjaxResponse(responseText, textStatus, XMLHttpRequest) {
    // Update dom
    initializeJobDescriptions();
    initializeAjaxPaging();
}

function initializeJobDescriptions() {
    // JOB DESCRIPTION TOOLTIPS
    $(".jobName").each(function() {
        var left = -($(this).width()) + 50;
        $(this).cluetip({
            local:            true,
            attribute:        "jobid",
            dropShadow:        false,
            positionBy:        "auto",
            showTitle:        false,
            sticky:            true,
            mouseOutClose:    true,
            width:            520,
            leftOffset:        left,
            topOffset:        -10,
            hoverIntent:    {
                sensitivity:  5,
                interval:     300,
                timeout:      100
            },
            clickThrough:     true
        });
    });

    // FOLD OUT TESTIMONIAL
    var foldEl = $("#searchResults .testimonial");
    foldEl.addClass("testimonialFancy closed");
    foldEl.append("<span class='toggle'>Open/close</span>");
    foldEl.append("<span class='close'>Close</span>");
    foldEl.children("div:first").append("<span class='linkMore'></span>").css({clear: "left"});
    foldEl.children("img").remove().prependTo(foldEl.children("div:first"));
    var title = foldEl.find("h2");
    var linkText = $('.txtReadStory').text();
    foldEl.find(".linkMore").text(linkText);
    foldEl.find(".linkMore, .toggle, .close").click(function() {
        if (foldEl.hasClass("closed")) {
            foldEl.animate({"right":"+=200"},
                          function() {
                              $(".linkMore").fadeOut("fast")
                          }).removeClass("closed");
        } else {
            foldEl.animate({"right":"-=200"},
                          function() {
                              $(".linkMore").fadeIn("fast")
                          }).addClass("closed");
        }
    });
}

$(document).ready(function() {

    // FUNCTIONS EXCLUSIVE FOR SEARCH PAGES
    if ($("body").hasClass("searchPage")) {

        // ADD FLASH HEADER
        params.wmode = "transparent";
        if ($("body").attr("id") == "home") {
            flashvars.expanded = true;
            expandHeight = 130;
            homePage = true;
        }
        function flashCallback(e) {
            if (e.success) {
                $("#container").addClass("flashEnabled");
            }
            ;
        }

        swfobject.embedSWF(eb_swfContent, "flashContent", "960", "420", "9.0.0", "", flashvars, params, attributes, flashCallback);

        // DISABLE Provincie and distance search WHEN Land IS NOT Nederland
        // Changed: run also onLoad
        onChangeCountryFunc = function() {
            if ($("select#country option").filter(":selected").val() != "NL") {

                // Remove region box
                $("select#province + div.newListSelected").css("display", "none");
                $("select#province").prev().css("display", "none");

                // Disable distance search
                $("#areaSearchItems").addClass("disabled");
                $("#areaSearchItems input").attr("disabled", true);
                $("#proximitySearch").attr("checked", false);
                $("#areaSearchItems input:text").attr("value", "");

                // Remove experience
                $("select#experience + div.newListSelected").css("display", "none");
                $("select#experience").prev().css("display", "none");
            } else {
                // Display experience
                $("select#experience + div.newListSelected").css("display", "block");
                $("select#experience").prev().css("display", "block");

                // Enable distance search
                $("#areaSearchItems").removeClass("disabled");
                $("#areaSearchItems input").removeAttr('disabled');

                // Display region box
                $("select#province + div.newListSelected").css("display", "block");
                $("select#province").prev().css("display", "block");
            }
        };
        $("select#country").change(onChangeCountryFunc);


        // Add handlers for recap form
        $("#searchRecapForm input").change(function() {
            $("#searchRecapForm").submit();
        });

        // Attach form submit handler for geocoding lookup
        $("#searchForm").submit(function() {
            return lookupCoordinates();
        });

        // MORE SEARCH OPTIONS
        var firstRun = true;
        $("#detailedSearch select").hide();
        $("#toggleSearchOptions #less").hide();
        $("#toggleSearchOptions a").click(function() {
            $("#detailedSearch").slideToggle("fast", function() {
                $("#toggleSearchOptions #less, #toggleSearchOptions #more").toggle();
                if (firstRun) {
                    $("#detailedSearch select").sSelect();
                    firstRun = false;
                    // Update state of form
                    onChangeCountryFunc();
                }
            });
            return false;
        });

        // Detect if "more search options pane" should be expanded?
        if (( $("#area").val() != "" ) || ( $("#contractType").val() != "" )
                || ( $("#education").val() != "" ) || ( $("#experience").val() != "" )) {
            $("#detailedSearch").show(1, function() {
                $("#toggleSearchOptions #less, #toggleSearchOptions #more").toggle();
                if (firstRun) {
                    $("#detailedSearch select").sSelect();
                    firstRun = false;
                    // Update state of form
                    onChangeCountryFunc();
                }
            });
        }

        // ENABLE INPUTS THROUGH CHECKBOX
        onChangeProximitySearch = function() {
            if ($("#proximitySearch").is(":checked")) {
                $("#areaSearchItems").removeClass("disabled");
                $("#areaSearchItems input:text").removeAttr("disabled");
            } else {
                $("#areaSearchItems").addClass("disabled");
                $("#areaSearchItems input:text").attr("disabled", true);
            }
        };
        $("#proximitySearch").change(onChangeProximitySearch);

        // NAV MAIN
        $("#navMain li").hover(
                              function() {
                                  swfPause();
                              },
                              function() {
                                  swfPlay();
                              }
                );

        // Initialize job descriptions
        initializeJobDescriptions();

        // Add ajax suppor for search result
        if ($("#searchResults").length > 0) {
            initializeAjaxPaging();
        }

    }

    // ADD JAVASCRIPT DEPENDENT ELEMENTS
    // print link
    var printLink = $("<span class='linkTypePrint'>" + labelPrintLink + "</span>");
    printLink.click(function() {
        window.print()
    });
    printLink.prependTo("#colRight, #detailContent #searchColRight");
    if ($("#colRight").length == 0) {
        printLink.insertAfter('#content > h1');
        printLink.addClass('right');
    }
    // erase list button
    var btnErase = $("<button class='btnType02'><span>" + labelEraseBtn + "</span></button>");
    btnErase.click(function() {
        $(".viewedJobsList li").remove();
        $.get(clearHistoryUrl);
        return false
    });
    btnErase.insertAfter(".viewedJobsList");
// ***************** ADD NEXT PART ***************************
	// Add hook to detect tab change: load map when changed to "map" tab
	var mapsInitialized = false;
	$('#searchResults').bind('tabsselect', function(event, ui) {
		if (ui.index == 1 && (!mapsInitialized) ) {
			mapsInitialized = true;
			
			loadMap();
		}
	});

    // LINK HANDLER
    $("a.externalLink").click(function() {
        window.open($(this).attr("href"));
        return false;
    });

    // SET LABEL TEXT AS INPUT VALUE
    $("input#searchField, input#postalCode").each(function() {
        var inputId = $(this).attr("id");
        var color = $(this).css("color");
        var label = $(this).siblings("label[for=" + inputId + "]");
        var inputValue = label.text().split(":")[0];
        label.hide();
        if ($(this).attr("value") == "") {
            $(this).attr("value", inputValue).css("color", "#888");
            $(this).focus(function() {
                if ($(this).attr("value") == inputValue) {
                    $(this).attr("value", "");
                }
                $(this).css("color", color);
            });
            $(this).blur(function() {
                if ($(this).attr("value") == "") {
                    $(this).attr("value", inputValue);
                    $(this).css("color", "#888");
                }
            });
        }
    });

    // TABS
    $(".tabs").prepend("<ul class='tabNav'></ul>");
    $(".tabs h2").each(function() {
        var text = $(this).text();
        var id = $(this).attr("id");
        var anchorId = text.split(" ").join("");
        anchorId = anchorId.replace(/[^a-z]/gi, '');
        ;
        $(this).next(".tabContent").attr("id", anchorId);
        $(this).remove();
        var li = $("<li></li>");
        li.attr("id", id).append("<a href='#" + anchorId + "'>" + text + "</a>");
        $(".tabNav").append(li);
    });
    var searchTabs = $(".tabs").tabs();


    // STYLE SELECT BOXES
    $("select:not(#detailedSearch select)").sSelect();

    // TESTIMONIALS COLLEAGUES
    $(".contentColleagues .testimonial").each(function() {
        var id = "testimonial" + $(".contentColleagues .testimonial").index(this);
        $(this).find(".linkMore").attr("href", "#" + id).show().css("display", "block");
        $(this).find("div.tExtraInfo").hide();
        var clone = $(this).clone();
        clone.appendTo($(this).parent());
        clone.attr("id", id);
        clone.hide();
        clone.children("div").show();
        clone.find("div.tBasicInfo img, .linkMore").hide();
        clone.find(".clipColleague").remove().clone().prependTo(clone.find("div:first"));
    });
    $(".contentColleagues .testimonial .linkMore").cluetip({
        local:            true,
        hideLocal:        false,
        attribute:        "href",
        dropShadow:        false,
        cluetipClass:    "testimonial",
        positionBy:        "auto",
        showTitle:        false,
        sticky:            true,
        mouseOutClose:    true,
        width:            430,
        topOffset:        50,
        leftOffset:        -20
    });

    // COLLAPSIBLE PANELS
    var toggles = $("table.panels .toggleHeader, .panels > :header")
    toggles.next().hide();
    toggles.toggle(
                  function() {
                      $(this).addClass("open").next().show();
                  },
                  function() {
                      $(this).removeClass("open").next().hide();
                  }
            );

    // Attach to bullet
    $('.iconMap').click(function() {
        searchTabs.tabs('select', 1); // switch to Map
        return false;
    });

    // Attach to links
    $('.reloadImage').click(function() {

        // Get ID of image
        var imageId = $(this).attr("image");
        var imageDom = document.getElementById(imageId);

        $("#" + imageId).each(function() {
            var orgSrc = $(this).attr("orgSrc");
            if (orgSrc == null) {
                $(this).attr(orgSrc, $(this).attr("src"));
                orgSrc = $(this).attr("src")
            }
            $(this).attr("src", orgSrc + "?t=" + Math.ceil(Math.random() * 10000));
        });

        return false;
    });

    // Handle "last-minute" updates of UI
    // For search form
    if ($("body").hasClass("searchPage")) {
        // Hide selectbox of region if necessary
        onChangeCountryFunc();
        // Update state of proximity search
        onChangeProximitySearch();
    }

});

