﻿// Brampton.ca Initialization Script

/*
Brampton.ca External Link Alert
*/

var pageUrl = window.location;

// ************************* //
// Run page-specific JavaScript functions
$(document).ready(DOMFixUp);
$(document).ready(EnforceDefaultContentClassLookupValidation);
$(document).ready(ShareItInit);

// Page to script mappings:
regexPatterns = [
					[new RegExp('(EditForm.aspx)'), KeywordsSearchFiltering, true /* run once */],
					[new RegExp('(NewForm.aspx)'), KeywordsSearchFiltering, true /* run once */]
				];

// Run page-specific functions:
var pagePath = window.location.pathname;
for (i = 0; i < regexPatterns.length; i++) {
    var item = regexPatterns[i];
    if (typeof (item) != undefined && item != null && item != undefined && item[0] != null) {
        if (item[0].test(pagePath)) {
            $(document).ready(item[1]);
            if (item[2] == true) {
                break; // we only need to run the function once if boolean is set to true.
            }
        }
    }
}

/* Content Class Default Lookup */
function EnforceDefaultContentClassLookupValidation() {
    var warned = false;

    var ddSelect = $("select[title=Content Class]");
    if (ddSelect.length <= 0) {
        return;
    }

    function validateContentClass() {
        var selectedValue = $("select[title=Content Class] :selected").text();
        var ddSelect = $("select[title=Content Class]");
        if (selectedValue.indexOf("Please select") != -1) {
            $(ddSelect).focus();
            if (!warned) {
                $(ddSelect).parent().append("<span class='ms-formvalidation'>You must specify a value for this required field.</span><br />");
                warned = true;
            }
            return false;
        }
        return true;
    }

    try {
        var oldOnClick = $("input[value=OK]").get(0).onclick;
    }
    catch (exp) { }

    try {
        var oldApprovePublish = $("#qaApprovePublish").attr("onclick");
        var oldCheckin = $("#qaCheckin").attr("onclick");
        var oldPublish = $("#qaPublish").attr("onclick");
    }
    catch (exp) { }

    ResetEventReceivers("input[value=OK]", oldOnClick);
    ResetEventReceivers("#qaApprovePublish", oldApprovePublish);
    ResetEventReceivers("#qaCheckin", oldCheckin);
    ResetEventReceivers("#qaPublish", oldPublish);

    function ResetEventReceivers(selector, oldEvent) {
        $(selector).each(function() {
            $(this).attr("onclick", "");
        });

        $(selector).click(function(e) {
            if (!validateContentClass()) {
                return false;
            }

            oldEvent.call(this, e);
        });
    }
}

function KeywordsSearchFiltering() {
    // ********************* //
    // Keywords Search Filtering

    var match = false;
    $(".ms-formfieldlabel").each(function() {
        var title = $(this).text();
        if (title.indexOf('Content Tags') != -1) {
            $(this).parent().parent().find('.ms-formfieldvaluecontainer').attr('id', 'CobKeywords');
            match = true;
        }
    });

    $('.ms-standardheader').each(function() {
        var title = $(this).text();
        if (title.indexOf('Content Tags') != -1) {
            $(this).parent().parent().find('.ms-long').parent().attr('id', 'CobKeywords');
            match = true;
        }
    });

    if (!match) {
        return;
    }

    // Append the keyword search filtering textbox
    $("#CobKeywords").prepend("<input id='CobKeywordsSearchBox' type='text' maxlength='255' size='50' /><br />");

    // Append add new keyword link
    var listName = "Tags";
    $("#CobKeywords").append("<a href='/Lists/" + listName + "/NewForm.aspx' target='_blank' style='font-size:12px; color:#3966bf; font-family:tahoma,sans-serif'>Add New Keyword</a>");

    // Make a copy of the list.
    var cachedList = $("#CobKeywords select[id$=SelectCandidate] option");
    var allOptions = {};
    $(cachedList).each(function(i) {
        var $curr = $(this);
        allOptions[$curr.val()] = $curr.text();
    });

    // Keyword filtering keyup event
    $("#CobKeywordsSearchBox").keyup(function() {
        var query;
        query = $("#CobKeywordsSearchBox").val().toLowerCase();

        if (query.length > 0) {
            setOptions("#CobKeywords select[id$=SelectCandidate]", allOptions);
            var options = $("#CobKeywords select[id$=SelectCandidate] option");
            options.each(function() {
                if ($(this).text().toLowerCase().indexOf(query) < 0) {
                    $(this).remove();
                }
            });
        }
        else {
            setOptions("#CobKeywords select[id$=SelectCandidate]", allOptions);
        }
    });

    function setOptions(selectId, filteredOptions) {
        var $select = $("" + selectId + "");
        $select.html('');

        var options = new Array();
        for (var i in filteredOptions) {
            options.push('<option value="');
            options.push(i);
            options.push('">');
            options.push(filteredOptions[i]);
            options.push('</option>');
        }
        $select.html(options.join(''));
    }
}

// ****** DOM fix *********** //
// change all <A> so it opens in a new window if the link is to a .pdf
// remove the <A> from a certain <H3 class="ms-WPTitle">
// ****** DOM fix *********** //
// change all <A> so it opens in a new window if the link is to a .pdf
// remove the <A> from a certain <H3 class="ms-WPTitle">
function DOMFixUp() {
    // fix up the PDF popup issue
    $('a[href$=".pdf"][target="_blank"]').each(function() { $(this).removeAttr('onclick'); });
    $('a[href$=".pdf"][target="_blank"]').each(function() { $(this).removeAttr('onclick'); });
    $('a[href$=".pdf"][target!="_blank"]').each(function() { $(this).attr('target', '_blank'); });
    $('a[href$=".PDF"][target!="_blank"]').each(function() { $(this).attr('target', '_blank'); });
    // fix the h3 in cases where the list is drop on as a web part on the page.
    $('H3.ms-WPTitle > a > nobr > span').each(function() { $(this).appendTo($(this).parent().parent().parent()); });
    $('H3.ms-WPTitle > a').remove();
}

// ****** Script for the highlights usercontrol rotator ******* //
var jsTimer = null;
var bDoingFade = false;

function ButClickedPlayPause() {
    if ($("img.hlPause").length > 0) {
        ShowPlayButton();
    }
    else {
        ShowPauseButton();
    }
}

function ShowPlayButton() {

    var pauseBut = $("img.hlPause");
    if (pauseBut.length > 0) {
        // currently showing the pauseButton
        hlStopTimer();
        var imgPath = pauseBut.attr('src').replace('pause', 'play');
        pauseBut.attr("src", imgPath);
        pauseBut.removeClass("hlPause").addClass("hlPlay");
    }
}

function ShowPauseButton() {
    var playBut = $("img.hlPlay");
    if (playBut.length > 0) {
        // currently showing the playbutton
        hlStartTimer();
        var imgPath = playBut.attr('src').replace('play', 'pause');
        playBut.attr("src", imgPath);
        playBut.removeClass("hlPlay").addClass("hlPause");
    }
}

function ButClicked(targetItem) {
    if (bDoingFade == true) {
        return;
    }

    bDoingFade = true;
    hlStopTimer();
    GoToImage(targetItem);
    ShowPlayButton();
}

function GoToImage(targetItem) {
    var currentDiv = $("div.hlSelected");
    var currentBut = $("img.hlSelected");
    var targetDiv = $("#highlightDiv" + targetItem);
    var targetBut = $("#highlightButton" + targetItem);

    // swap images on the buttons
    var currentImgSRC = currentBut.attr('src').replace('Buttonon', 'Buttonoff');
    var targetImgSRC = targetBut.attr('src').replace('Buttonoff', 'Buttonon');
    currentBut.attr("src", currentImgSRC);
    targetBut.attr("src", targetImgSRC);

    targetDiv.css("z-index", 10);
    targetDiv.fadeIn("slow", function() {
        targetDiv.css("opacity", "0.97");
        currentDiv.fadeOut("slow");
        currentDiv.css("opacity", "0.0");
        currentDiv.css("z-index", 9);
        bDoingFade = false;
    });

    currentBut.removeClass("hlSelected").addClass("hlUnselected");
    currentDiv.removeClass("hlSelected").addClass("hlUnselected");
    targetBut.removeClass("hlUnselected").addClass("hlSelected");
    targetDiv.removeClass("hlUnselected").addClass("hlSelected");
}

function GoToNextImage() {
    // get max number
    var maxValue = $("#hlCount").val();
    var intMaxValue = parseInt(maxValue, 10);

    // get the current DIV
    var currentDiv = $("div.hlSelected");
    var curItemId = currentDiv.attr("id");
    var itemNumber = curItemId.substring(curItemId.length - 1);
    var intValue = parseInt(itemNumber, 10);

    if ((intValue + 1) == intMaxValue) {
        GoToImage(0);
    }
    else {
        GoToImage(intValue + 1);
    }
    hlStartTimer();
}

// do the javascript timer
function hlStartTimer() {
    var maxValue = $("#hlCount").val();
    if (maxValue <= 1) {
        return;
    }

    if (jsTimer != null) {
        hlStopTimer();
    }

    jsTimer = setTimeout("GoToNextImage ()", 10000);
}

function hlStopTimer() {
    if (jsTimer != null) {
        clearTimeout(jsTimer);
        jsTimer = null;
    }
}

// ******* Sharing Toolbar ****** //

function ShareItInit() {
    $(".shareItButton").click(function() {
        if ($(".shareItPanel").is(":hidden")) {
            $(".shareItPanel").slideDown("slow");
        } else {
            $(".shareItPanel").fadeOut();
        }
    });

    $(".closeShareIt").click(function() {
        $(".shareItPanel").fadeOut();

    });
}

// ******* do nothing ******//
function DoNothing() {
}

// ************************  //

function isExternal(element) {
    if (!element.href || element.href == '') {
        return false;
    }
    else if (element.href.indexOf('javascript') >= 0) {
        return false;
    }

    if (element.hostname) {
        if (element.hostname.indexOf('.brampton.ca') > 0) {
            // do nothing
        }
        else if (element.hostname.indexOf('.bramptonmaps.ca') > 0) {
            // do nothing
        }
        else if (element.hostname.indexOf('.bramptonresults4.ca') > 0) {
            // do nothing
        }
        else if (element.hostname !== window.location.hostname) {
            return true;
        }
    }
    return false;
} //end of isExternal function

jQuery(document).ready(function() {
    $("a").each(function() {
        if (isExternal(this)) {
            var oldHref = this.href;
            this.setAttribute("href", L_Menu_BaseUrl + "/_layouts/brampton/internet/externalredir.aspx?" + escape(oldHref));
            this.target = "_blank";
        }

    });
});
