/*
Helpers for forms
*/
/* loading gif is site specific and should be included in site images */
var loaderHtml = '<div id="loader"><p><img src="/@@/tfws.icons/loading.gif" /></p>'+
                 '<p>Contacting server, please be patient.</p></div>';
var errorHtml = '<div id="loader"><p>A error has occurred contacting the server.'+
                 ' Please try again later.</p></div>';
// Validation errors
var errorStartTag = '<div class="error">';
var errorEndTag = '</div>';
var errorEmpty = 'This is a required field!';
var errorEmail = 'Please enter a valid email address!';
//Validation routines
isEmpty = function(v) {
    return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
}
validateEmail = function(v) {
    return /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
}

/*
* Create a
* <span>preText <span class="highlighted">term</span> postText</span>
* around each search term
*/

function highlight_search_terms_from_uri() {
    var body = $('body');
    if (body) {
        var query = new Query();
        var terms = query.chooseBest().split(' ');
        for ( var i = 0; i < terms.length; i++ ) {
            highlight_search_terms(terms[i], body);
        }
    }
}
Event.observe(window, 'load', highlight_search_terms_from_uri, false);

function highlight_search_terms(term, container) {
    if (term == '') {
        return;
    }
    for (var i = 0; i < container.childNodes.length; i++) {
    var node = container.childNodes[i];

    if (node.nodeType == 3) {
        // Text node
        var data = node.data;
        var data_low = data.toLowerCase();
        if (data_low.indexOf(term) >= 0) {
            //term found!
            var new_node = document.createElement('span');

            node.parentNode.replaceChild(new_node, node);

            var result;
            while ((result = data_low.indexOf(term)) != -1) {
                new_node.appendChild(document.createTextNode(
                data.substr(0, result)));
                new_node.appendChild(create_highlighted_node(
                document.createTextNode(data.substr(
                result, term.length))));
                data = data.substr(result + term.length);
                data_low = data_low.substr(result + term.length);
            }
            new_node.appendChild(document.createTextNode(data));
        }
        } else {
            // Keep going onto other elements
            highlight_search_terms(term, node);
        }
    }
}

function create_highlighted_node(child) {
    var node = document.createElement('span');
    node.setAttribute('class', 'highlighted');
    node.attributes['class'].value = 'highlighted';
    node.appendChild(child);
    return node;
}

// set publictools menu item to selected
function sectionMenuInitialize() {
    var pb = $('siteactions');
    if (pb == null) {
        return;
    }
    var links = $A(pb.getElementsByTagName('a'));
    var loc = window.location;
    var linkslen = links.length;
    for (var i=0; i<linkslen;i++) {
        if (links[i].href == loc) {
            links[i].setAttribute("class", 'selected');
            break;
        }
    }

}
Event.observe(window, 'load', sectionMenuInitialize, false);

// QUERY object library -------------------------------------------

// constructor ------------------------
function Query () {
    var qString = document.referrer.replace(/^[^\?]+\??/,'') || 
         document.location.href.replace(/^\?/,'');
    qString = qString.replace(/#[^#]*$/, '');
    if ( qString ) {
        this.queryString = qString;
        this.params = this.parseQuery();
    }
}

// -----------------------------------
Query.prototype.parseQuery = function () {  
    var Params = new Object();
    if ( ! this.queryString ) return Params;
    var Pairs = this.queryString.split(/[&;]/);

    for ( var i = 0; i < Pairs.length; i++ ) {
        var KeyVal = Pairs[i].split('=');
        if ( ! KeyVal.length == 2 ) continue;
        if ( ! ( KeyVal[0] || KeyVal[1] ) ) continue;
        var key = unescape( KeyVal[0] );
        var val = unescape( KeyVal[1] );
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}

// -----------------------------------
Query.prototype.chooseBest = function () {
    // build an associative array of terms to scores
    var scoredParams = this.scoredParams();

    var max = 0;
    var choice = '';
    for ( var qVal in scoredParams ) {
        if ( scoredParams[qVal] > max ) {
        choice = qVal;
        max = scoredParams[qVal];
        }
    }
    return choice;
}

// -----------------------------------
Query.prototype.scoredParams = function () {
    var params = this.params;

    var Scored = new Object(); // Scored["value"] = numeric_score_of_value

    for ( var key in params ) {
        var val = params[key];

        var weight = 0;

        // count things that look like words, min of 3 "letters"
        var wordlikes = val.match(/(\w[-'\w]+\w\s)|(\w[-'\w]+\w)$/gi);
        weight += wordlikes ? wordlikes.length : 0;

        // we know some keys are real indicators so we'll score on them too
        if ( key.match(/^(q|p)$/) ) weight += 2;
        if ( key.match(/query|search/i) ) weight++;

        // heavily discount that which we know to be wrong
        var badChars = val.match(/[^-a-zA-Z'" ]/g);
        weight -= badChars ? ( badChars.length * 2 ) : 0;

        // value probably shouldn't talk about searches or queries
        weight -= val.match(/query|search/i) ? 1 : 0;

        Scored[val] = weight;
    }
    return Scored;
}

function pngFixForIE() {
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

    if ((version >= 5.5) && (document.body.filters) && (version < 7)) {
        for(var i=0; i<document.images.length; i++) {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText 
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
                + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
                img.outerHTML = strNewHTML
                i = i-1
            }
        }
    }
}

Event.observe(window, 'load', pngFixForIE, false);
