﻿/**
 * A simple querystring parser.
 * Example usage: var q = $.parseQuery(); q.fooreturns  "bar" if query contains "?foo=bar"; multiple values are added to an array. 
 * Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
 * http://actingthemaggot.com/jquery
 *
 * Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 **/
jQuery.parseQuery = function(qs,options) {
	var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {};
	jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
		p = p.split('=');
		p[1] = o.f(p[1]);
		params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
	});
	return params;
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


function getBaseDomain(url) {
    if (url.indexOf(":") == 5) {
        // https
        return url.substring(8, url.indexOf('/', 8));
    } else {
        // http
        return url.substring(7, url.indexOf('/', 7));
    }

}

// Check for file links
var possibleExtensions = new Array("pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "zip", "jpg", "gif");
// var possibleExtensions = new Array("pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "zip", "jpg", "gif", "");
var linksExtensions = [];

function getLinkExtension(link) { return getValidExtention(link.href.substring(link.href.length - 4).replace(".", "")); }
function checkIsMailLink(link) { if (link.href.substring(0, 7) == "mailto:") { return true; } return false; }
function checkIsExternalLink(link) { if (link.href.substring(0, 4) == "http") { return true; } return false; }

function checkIsSocialMedia(link) {
    var result = false;
    var media = new Array("facebook", "twitter", "nixle", "youtube");

    for (var i in media) {
        var medianame = media[i].toLowerCase();
        var index = link.href.indexOf(medianame);
        if (index > -1) { result = true; }
    }
    return result;
}

function getValidExtention(ext) {
    var thisExt;
    thisExt = null;
    for (var i in possibleExtensions) {
        if (ext == possibleExtensions[i]) {
            thisExt = ext;
        }
    }
    return thisExt;
}

function checkIsDomainException(link) {

    var thisDomain = getBaseDomain(link.href);
    var domainExceptions = new Array("baltimore.customerservicerequest.org", "localhost", "69.59.141.170");
    //var domainExceptions = new Array("business.baltimorecity.gov", "discuss.baltimorecity.gov", "dev.baltimorecity.gov", "apps.baltimorecity.gov", "test.baltimorecity.gov", "www.baltimorecity.gov", "staging.baltimorecity.gov", "baltimorecity.gov", "baltimore.customerservicerequest.org", "cityservices.baltimorecity.gov", "localhost", "69.59.141.170", "maps.baltimorecity.gov", "mayr-m-karr", "openbaltimore.baltimorecity.gov", "data.baltimorecity.gov", "moit-b-wham2", "www.google.com");
    for (var i in domainExceptions) {
        if (domainExceptions[i] == thisDomain) {
            return true;
            break;
        }
    }
    return false;
}

function getCurrentStyle(elem, prop) {
    if (elem.currentStyle) {
        var ar = prop.match(/\w[^-]*/g);
        var s = ar[0];
        for (var i = 1; i < ar.length; ++i) {
            s += ar[i].replace(/\w/, ar[i].charAt(0).toUpperCase());
        }
        return elem.currentStyle[s]
    }
    else if (document.defaultView.getComputedStyle) {
        return document.defaultView.getComputedStyle(elem, null).getPropertyValue(prop);
    }
}

// highlight search terms from SERPs
var highlightTermsIn = function(jQueryElements, terms) {
    var wrapper = ">jQuery1<b style='font-weight:normal;color:#000;background-color:rgb(255,255,102)'>jQuery2</b>jQuery3<";
    for (var i = 0; i < terms.length; i++) {
        var regex = new RegExp(">([^<]*)?(" + terms[i] + ")([^>]*)?<", "ig");
        jQueryElements.each(function(i) {
            jQuery(this).html(jQuery(this).html().replace(regex, wrapper));
        });
    };
}

// returns array of unique search terms (words, phrases) found in value
var parseSearchTerms = function(value) {
    // split string on spaces and respect double quoted phrases
    var splitRegex = /(\u0022[^\u0022]*\u0022)|([^\u0022\s]+(\s|jQuery))/g;
    var rawTerms = value.match(splitRegex);
    var terms = [];
    if (rawTerms) {
        for (var i = 0; i < rawTerms.length; i++) {

            // trim whitespace, quotes, apostrophes and query syntax special chars
            var term = rawTerms[i].replace(/^[\s\u0022\u0027+-][\s\u0022\u0027+-]*/, '').replace(/[\s*~\u0022\u0027][\s*~\u0022\u0027]*jQuery/, '').toLowerCase();
            // ignore if <= 2 chars
            if (term.length <= 2) {
                continue;
            }

            // ignore stopwords
            var stopwords = ["about", "are", "from", "how", "that", "the", "this", "was", "what", "when", "where", "who", "will", "with", "the"];
            var isStopword = false;
            for (var j = 0; j < stopwords.length; j++) {
                if (term == stopwords[j]) {
                    isStopword = true;
                    break;
                }
            }

            if (isStopword === true) {
                continue;
            }

            terms[terms.length] = term;
        }
    }
    return terms;
}

jQuery(document).ready(function() {

    jQuery("img").parent("a").addClass("codeBehind");

    // Show menu items when tabbed to
    jQuery("a.skipNavLink").focus(function() {
        jQuery("#accessMenu").removeClass("offPage");
    }).blur(function() {
        jQuery("#accessMenu").addClass("offPage");
    });
    jQuery(".videoControls a").focus(function() {
        jQuery(".videoControls").removeClass("offPage");
    }).blur(function() {
        jQuery(".videoControls").addClass("offPage");
    });

    // Alert
    jQuery(".alertLink").click(function() {
        // IE cant handle the floating elements properly, remind container it contains floats...
        if (jQuery.browser.msie) {
            jQuery(".alertsContainer:visible").parent().css("overflow", "auto");
        }
        // Toggle alerts visibility with animation
        jQuery(".alertsContainer:visible").slideUp("fast");
        jQuery(".alertsContainer:hidden").slideDown("fast").focus();
        jQuery(this).toggleClass("alertLinkOpen");
    });

    // Link Dressings
    jQuery('a:not("#dnn_AccessPane a,a[name],.ControlPanel a,.recaptcha_widget_div a"), #webmaster a').each(function() {

        var myExtension = getLinkExtension(this);
        var IsExternalLink = checkIsExternalLink(this);
        var IsDomainException = checkIsDomainException(this);
        var IsMailLink = checkIsMailLink(this);
        var IsSocialMedia = checkIsSocialMedia(this);
        var IsFileLink = getLinkExtension(this);
	var IsBaltimoreDomain = (this.href.indexOf("baltimorecity.gov") != -1)?true:false;

        if (IsExternalLink && !IsDomainException && !IsFileLink && !IsSocialMedia && !IsBaltimoreDomain) {
            jQuery(this).append('<span class=\"offPage\">(External Link)</span>');
            if (!jQuery(this).hasClass('iconLink') && !jQuery(this).hasClass('codeBehind') && !jQuery(this).parent().hasClass('TitleCell')) {
                this.className = this.className + " linkIcon extLinkIcon";
            }
        }

        if (IsMailLink) {
            jQuery(this).append('<span class=\"offPage\">(Email Link)</span>');
            if (!jQuery(this).hasClass('iconLink') && !jQuery(this).hasClass('codeBehind')) {
                this.className = this.className + " linkIcon mailtoIcon";
            }
        }

        if (IsSocialMedia) {
            jQuery(this).append('<span class=\"offPage\">(External Link)</span>');
            if (!jQuery(this).hasClass('iconLink') && !jQuery(this).hasClass('codeBehind')) {
	        var socialname = this.hostname.substring(this.hostname.indexOf(".") + 1, this.hostname.lastIndexOf("."));
	        this.className = this.className + " linkIcon " + socialname + "Icon";
    	    }
        }

        for (var i in possibleExtensions) {
            if (myExtension == possibleExtensions[i]) {
                if (!jQuery(this).hasClass('iconLink') && !jQuery(this).hasClass('codeBehind') && !jQuery(this).parent().hasClass('TitleCell')) {
                    this.className = this.className + " linkIcon " + myExtension + "Icon";
                }
                break;
            }

            var fileClass = possibleExtensions[i].toLowerCase() + "Icon";
            var fileExtension = fileClass.replace("Icon", "").toUpperCase();
            if (fileClass == "Icon") {
                fileExtension = "Unknown";
            }

            if (jQuery(this).hasClass(fileClass)) {
                jQuery(this).append('<span class=\"offPage\">(' + fileExtension + ' File)</span>');
            }

        }

    }); // End Link Dressings

    for (var i = 0; i < possibleExtensions.length; i++) {
        var thisClass = possibleExtensions[i] + "Icon";

        if (jQuery('a').hasClass(thisClass)) { linksExtensions.push(possibleExtensions[i]); }

        // Check for upper case
        var thisClassUpper = possibleExtensions[i].toUpperCase() + "Icon";
        if (jQuery('a').hasClass(thisClassUpper)) { linksExtensions.push(possibleExtensions[i]); }
    }

    if (linksExtensions.length > 0) {
        jQuery('#viewerDownloads').css('display', 'block');
        for (var i in linksExtensions) {
            var le = linksExtensions[i];
            jQuery('#' + le + 'Viewer').css('display', 'block');
        }
    }

    // CSS 3 for non-supporting browsers
    if (jQuery.browser.msie) {
        jQuery(".announcementsItem:last-child, .announcementsAlternateItem:last-child").addClass("announcementsLastChild");
        jQuery(".alertItem:last-child").addClass("lastAlert");
    }


    jQuery(".copyLink").click(function(e) {
        e.preventDefault();
        var myElement = jQuery(".autoselect").get(0);
        if (window.getSelection) {
            var selection = window.getSelection();
            if (selection.setBaseAndExtent) { /* for Safari */
                //var selection = window.getSelection();
                //selection.setBaseAndExtent(myElement, 1, myElement, 1);
                alert("Your browser does not support auto-copy. You will have to manually select and copy this text.");
            } else { /* for FF, Opera */
                var range = document.createRange();
                range.selectNodeContents(myElement);
                selection.removeAllRanges();
                selection.addRange(range);
                alert("Text has been selected. To copy, press Ctrl+C or right click and select Copy.");
            }
        } else { /* for IE */
            var range = document.body.createTextRange();
            range.moveToElementText(myElement);
            range.select();
            range.execCommand("Copy");
            alert("Selection has been copied to the clipboard!");
        }
    });

    jQuery('#leftColumn h2').each(function() {
        var thisEl = this;
        var parentAnchor = thisEl.parentNode.parentNode;
        var parentListItem = thisEl.parentNode.parentNode.parentNode;

        if (jQuery(parentListItem).hasClass('rmItem')) {

            thisEl.setAttribute("class", "menuSectionH2");

            parentListItem.setAttribute("class", "menuSectionItem");
            parentListItem.appendChild(thisEl);
            parentListItem.removeChild(parentAnchor);

        }
    });

    jQuery('#leftColumn a').each(function() {
        this.removeAttribute('title');
    });



});    // End Document Ready
