if (window.org == null) window.org = {};
if (org.thevoterguide == null) org.thevoterguide = {};
org.thevoterguide.jQuery = window.jQuery;

(function (vgt) {
    var $ = vgt.jQuery;
    var argsToA = function(args, n) {
        var a = [];
        for (var i = n; i < args.length; i++)
            a.push(args[i]);
        return a;
    }
    
    var log = function() {
        if (window.console)
            try {
                console.log.apply(console, arguments);
            } catch (e) {}
    };

    $.extend(vgt, {

swfEmbed: function(url) {
    if ($.browser.msie)
        document.write('<object class="vgt-youtube"><param name="movie" value="' + url + '"/></object>');
    else
        document.write('<embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true"/>');
},

// BEGIN PUBLIC API

/**
 * Bind a callback function to an VGT user event. Valid event topics are (callback function parameters are listed
 * between curly brackets:
 * <ul>
 *   <li>vgtHideChoice {choiceId}</li>
 *   <li>vgtShowChoice {choiceId}</li>
 *   <li>vgtCompare {choiceId1, choiceId2}</li>
 *   <li>vgtSelect {choiceId}</li>
 *   <li>vgtUnselect {choiceId, passive}</li>
 *   <li>vgtSetNote {note}</li>
 * </ul>
 *
 * @param topic {String}
 * @param callback {Function}
 */
bind: function(topic, callback) {
    var fct = function() {
        callback.apply(null, argsToA(arguments, 1));
    }
    callback.vgtcb = fct;

    $(function() { $("#vgt").bind(topic, fct); });
},

/**
 * Unbinds a VGT user event callback.
 *
 * @param topic
 * @param callback
 * @see #bind()
 */
unbind: function(topic, callback) {
    $(function() { $("#vgt").unbind(topic, callback.vgtcb); });
},

/**
 * Returns the IDs of the two choices in currently in the comparison pane.
 * @return {Array<Number>} An array of length 2.
 */
getComparison: function() {
    return this._COMPARING_IDS.concat();
},

/**
 * Sets the current comparison. The two IDs must be the IDs of choices in the race displayed by the current
 * page.
 *
 * @param id1 {Number} the left-side choice
 * @param id2 {Number} the right-side choice
 */
setComparison: function(id1, id2) {
    this.addToComparison(id1, id2);
},

// END PUBLIC API

trigger: function(topic, arg1) {
    var a = argsToA(arguments, 1);
    $(function() { $("#vgt").trigger(topic, a); });
},

/* track an Ajax action via Google Analytics */
track: function(key) {
    if (this.pageTracker) {
        try {
            this.pageTracker._trackPageview("/v/" + this.AFF + "/" + key);
        } catch (e) {}
    }
},

editNotes: function(objATag) {
    var objSpanTag = objATag.parentNode;
    $(objSpanTag.previousSibling).removeClass("display-none");
    $(objSpanTag).addClass("display-none");

    this.track("js/notes/edit/" + this.DATA.race.id);
},

cancelEditNotes: function(objATag) {
    var objSpanTag = objATag.parentNode.parentNode;
    $(objSpanTag.nextSibling).removeClass("display-none");
    $(objSpanTag).addClass("display-none");

    this.track("js/notes/cancel/" + this.DATA.race.id);
},

notesEditSuccess: function(strValue) {
    var textSpan = document.getElementById("vgt-note-text");
    var bTag = textSpan.firstChild;
    bTag.innerHTML = "";
    bTag.appendChild(document.createTextNode(strValue));

    $(textSpan.previousSibling).addClass("display-none");
    $(textSpan).removeClass("display-none");

    $("#vgt-notes-cancel").removeClass("display-none");
    this.trigger("vgtSetNote", strValue);
},

showFlagForm: function(pageAnchor, raceId) {
    $(".vgt-abuse").remove();
    
    pageAnchor = $(pageAnchor);
    var div = $('<div class="vgt-abuse vgt-callout-outer"><div class="vgt-callout"></div>' +
                '<h2>Report Abusive</h2>' + 
                '<label for="vgt-abuseComment">Reason (required)</label>' +
                '<textarea id="vgt-abuseComment"></textarea>' +
                '<div><input type="button" value="Report"/> <input type="button" value="Cancel"/></div>' +
                '</div>');

    $("input[value='Report']", div).click(function() {
        var reason = $("textarea", div).val();
        
        if (reason.match(/\S/)) {
            $.ajax({
                url: "report-abuse.do",
                data: {
                    raceId: raceId, 
                    entryId: pageAnchor.parent().attr("entry-id"), 
                    reason: reason
                }
            });
            div.remove();
        }
    });
    
    $("input[value='Cancel']", div).click(function() {
        div.remove();
    });
    
    div.hide();
    
    var addTo = $("#vgt");

    var anchorPos = pageAnchor.offset();  
    var parentPos = addTo.offset();  

    div.css({left: (anchorPos.left - parentPos.left + pageAnchor.width() + 9) + "px", top: (anchorPos.top - parentPos.top - 21) + "px"});
    
    div.appendTo(addTo);
    div.fadeIn();
},

onLike: function(url) {
    if (/\bid=(\d+)\b/.exec(url)) {
        this.track("js/like/" + RegExp.$1);
    }
},
        
hideLikePanel: function() {
    $(".vgt-fblike").fadeOut();
    window.clearTimeout(this._fblikeTO);
    this._fblikeTO = null;
},

showLikePanel: function(canonUrl, choiceId, pageAnchor) {
    this.hideLikePanel();
    if (this.likePanelIsOff()) return;
    
    var url = canonUrl + "?id=" + choiceId;
    var div = $('<div class="vgt-callout-outer vgt-fblike"><div class="vgt-callout"></div>' +
                '<h2>Endorse on Facebook</h2><div style="position:relative;"><fb:like href="' + url + '" width="325" action="recommend"></div></fb:like>' + 
                '<div class="vgt-fblike-ignore">' +
                '<a href="#" onclick="org.thevoterguide.turnOffLikePanel();return false;">Don\'t ask me again</a>' +
                '</div>' +
                '<div class="vgt-fblike-next">' +
                '<a href="#" onclick="org.thevoterguide.goNext();return false;">Next Race</a> | ' +
                '<a href="#" onclick="org.thevoterguide.hideLikePanel();return false;">Hide</a>' +
                '</div>' + 
                '</div>');
    div.hide();
    
    var addTo = $("#vgt");

    var anchorPos = pageAnchor.offset();  
    var parentPos = addTo.offset();  

    div.css({left: (anchorPos.left - parentPos.left + pageAnchor.width() + 7) + "px", top: (anchorPos.top - parentPos.top - 12) + "px"});
    
    div.appendTo(addTo);
    FB.XFBML.parse(div[0]);
    div.fadeIn();
    
    // need to hide it only if not focused in it
//    this._fblikeTO = window.setTimeout(function() { org.thevoterguide.hideLikePanel(); }, 20000);
},

turnOffLikePanel: function() {
    this.hideLikePanel();
    document.cookie = 'fblike=off; path=/';    
},

likePanelIsOff: function() {
    return String(document.cookie).indexOf('fblike=off') >= 0;  
},

selectionSuccess: function(objForm, strXML) {
    this._setForm(objForm, objForm.select.value == "true");
    if (strXML.match(/remove\:\[\s*([ \d]+)\s*\]/)) {
        var ids = RegExp.$1;
        ids = ids.split(/\D+/g);
        for (var i = 0; i < ids.length; i++) {
            var otherForm = document.getElementById("vgt-sel-form-" + ids[i]);
            if (otherForm)
                this._setForm(otherForm, false);

            this.track("js/passive-unselect/" + ids[i]);
            this.trigger("vgtUnselect", ids[i], true);
        }
    }

    this.highlightNext(this.getSelectedCount() >= this.CHOOSE_COUNT);
},

highlightNext: function(bOk) {
    if (bOk == null) bOk = this.getSelectedCount() >= this.CHOOSE_COUNT;

    var navs = $(document.getElementsByName("vgt-nav-next"));
    navs.parent()[bOk ? "addClass" : "removeClass"]("vgt-bnav-ready");

    if (bOk && navs.length > 0 && navs[0].focus)
        navs[0].focus();
},

goNext: function() {
    var href = $("*[name=vgt-nav-next]").attr("href");
    if (href)
        document.location.href = href;
},

getSelectedCount: function() {
    var count = 0;
    var elms = document.getElementsByName("select");
    for (var i = 0; i < elms.length; i++) {
        var elm = elms[i];
        if (String(elm.parentNode.getAttribute("vgtid")).indexOf("vgt-sel-form") == 0 &&
                elm.value == "false")
            count++;
    }
    return count;
},

_setForm: function(objForm, bSelect) {
    var imageDiv = $(objForm).find(".formimage")[0];

    if (bSelect) {
        if (imageDiv)
            $(imageDiv).addClass("on");
        objForm.select.value = "false";
    } else {
        if (imageDiv)
            $(imageDiv).removeClass("on");
        objForm.select.value = "true";
    }
},

_firstChildElm: function(objElm, intStart) {
    for (var i = intStart || 0; i < objElm.childNodes.length; i++) {
        var c = objElm.childNodes[i];
        if (c.nodeType == 1) return c;
    }
    return null;
},

_selectionEmpty: function() {
    return this._COMPARING_IDS[0] == null && this._COMPARING_IDS[1] == null;
},

toggleExpanded: function(objHeaderDiv, e, bExpand) {
    var answerDiv = objHeaderDiv.nextSibling;

    var bResult = null;

    if ($(answerDiv).hasClass("display-none") && (bExpand == null || bExpand)) {
        if (!this._selectionEmpty()) {
            $(answerDiv).removeClass("display-none").addClass("vgt-clearfix");
            $(objHeaderDiv).find("img").addClass("vgt-excol-collapse");
            bResult = true;
        }
    } else if (bExpand == null || !bExpand) {
        $(answerDiv).addClass("display-none").removeClass("vgt-clearfix");
        $(objHeaderDiv).find("img").removeClass("vgt-excol-collapse");
        bResult = false;
    }

    // Hack for IE rendering bug
    var allQuestions = objHeaderDiv.parentNode.parentNode;
    allQuestions.style.display = "none";
    allQuestions.style.display = "";

    if (bResult != null && e && (e.ctrlKey || e.altKey)) {
        var questionsDiv = document.getElementById("vgt-questions");
        if (questionsDiv) {
            var divs = questionsDiv.childNodes;

            for (var i = 0; i < divs.length; i++) {
                var anotherATag = divs[i].firstChild;
                if (anotherATag != objHeaderDiv)
                    this.toggleExpanded(anotherATag, null, bResult);
            }
        }
    }
},

addToComparison: function(choiceId, choiceTwo) {
    var ids;
    if (choiceTwo) {
        ids = [choiceId, choiceTwo];
    } else if (this._COMPARING_IDS[0]) {
        ids = [this._COMPARING_IDS[0], choiceId];
    } else {
        ids = [choiceId, this._COMPARING_IDS[1]];
    }

    this._showAnswersFor(ids);
    this._syncSelects();
    this._syncCompareImages();

    this.track("js/compare/" + choiceId);
    this.trigger("vgtCompare", ids[0], ids[1]);
},

onComparisonSelectChange: function(objSelectTag) {
    var ids = [];
    var i = 0, s = null;
    while (s = document.getElementById("vgt-compareselect-" + i)) {
        ids.push(s.value);
        i++
    }
    this._showAnswersFor(ids);
    this._syncCompareImages();

    this.track("js/compare/" + objSelectTag.value);
},

_COMPARING_IDS: [null, null],

_showAnswersFor: function(arrChoiceIds) {
    var bWasEmpty = this._selectionEmpty();

    this._COMPARING_IDS = arrChoiceIds;

    var questionsDiv = document.getElementById("vgt-questions");
    if (!questionsDiv) return;
    var divs = $("> *", questionsDiv);

    for (var i = 0; i < divs.length; i++) {
        var qDiv = divs[i];
        var answersDiv = qDiv.childNodes[1];

        var qId = null;
        if (qDiv.id.indexOf("question_") == 0)
            qId = qDiv.id.substring("question_".length);
        else if (qDiv.id == "vgt-bio-fields")
            ;
        else
            continue;

        if (!answersDiv) {
            answersDiv = document.createElement("div");
            answersDiv.className = "vgt-comparison-answer display-none";
            qDiv.appendChild(answersDiv);
        }

        // Clear current contents
        answersDiv.innerHTML = "";
        answersDiv.style.width = Math.max(0, answersDiv.parentNode.clientWidth - 20) + "px"; // width minus right and left padding

        for (var j = 0; j < arrChoiceIds.length && j < this.CHOICE_COUNT; j++) {
            var choiceId = arrChoiceIds[j];

            var cacheDiv = document.getElementById(qId ? "answer_" + qId + "_" + choiceId : "biovalues_" + choiceId);

            var c;
            if (cacheDiv) {
                c = cacheDiv.cloneNode(true);
                c.removeAttribute("id");
            } else {
                c = document.createElement("div");
                c.innerHTML = "&nbsp;";
            }

            c.className = "answer answer" + j + " answerOf" + this.CHOICE_COUNT;
            answersDiv.appendChild(c);
        }

        // collapse if none selected...
        if (arrChoiceIds.length == 0)
            this.toggleExpanded(qDiv.firstChild, null, false);
    }

    if (arrChoiceIds.length > 0) {
        if (bWasEmpty) {
            for (var i = 0; i < divs.length; i++) {
                var anotherATag = divs[i].firstChild;
                this.toggleExpanded(anotherATag, null, true);
            }
        } else {
            this._ensureAtLeastOneExpanded();
        }
    }
},

_syncSelects: function() {
    var arrChoiceIds = this._COMPARING_IDS;
//    var bFocus = true;

    var selects = $(".vgt-comparison-sel");
    for (var i = 0; i < selects.length; i++) {
        var s = selects[i];
        var newValue = arrChoiceIds.length > i ? arrChoiceIds[i] : null;
        if (newValue != s.value) {
            s.value = newValue;
/*
            if (bFocus) {
                s.focus();
                bFocus = false;
            }
*/
        }/* else if (i == selects.length - 1 && bFocus) {
            s.focus();
        }*/
    }
},

_syncCompareImages: function() {
    var i = 0, s = null;
    while (s = document.getElementById("vgt-compareselect-" + i)) {
        var imageDrop = s.parentNode.previousSibling.firstChild.firstChild.firstChild;
        var cachedImage = document.getElementById("vgt-image-" + s.value);
        if (cachedImage) {
            imageDrop.src = cachedImage.src;
            $(imageDrop).removeClass("blank");
        } else {
            imageDrop.src = document.getElementById("vgt-clear-img").src;
            $(imageDrop).addClass("blank");
        }

        i++
    }
},

_ensureAtLeastOneExpanded: function() {
    var questionsDiv = document.getElementById("vgt-questions");
    if (!questionsDiv) return;
    var divs = questionsDiv.childNodes;
    var oneOpen = false;

    for (var i = 0; !oneOpen && i < divs.length; i++) {
        var qDiv = divs[i];
        oneOpen = !$(qDiv.childNodes[1]).hasClass("display-none");
    };

    if (!oneOpen && divs.length > 0) {
        this.toggleExpanded(divs[0].firstChild, null, true);
    }
},

showLangSelect: function(url) {
    var div = document.getElementById("vgt-language-select");
    if (div) {
        this._INSTURL = url;
        this._showDialog(div, function() { $("#vgt-language-select .vgt-panel").focus(); });
        this._lastlang = $("input:checked", div).val();
        return true;
    }
},

hideLangSelect: function() {
    $("#vgt-language-select").addClass("display-none");
},

selectLanguage: function(lang) {
    if (this._lastlang != lang) {
        this.hideLangSelect();
        var s = document.location.search;
        s = s.replace(/[\&\?]l=\w+\b/g, "");
        document.location.search = s + (s ? "&" : "?") + "l=" + lang;
    }
},
        
showInstructions: function(url) {
    var div = document.getElementById("vgt-instructions");
    if (div) {
        this._INSTURL = url;
        this._showDialog(div, function() { $("#vgt-choose-btn").focus(); });
        return true;
    }
},

ignoreInstructions: function() {
    window.location.href = this._INSTURL;
},

hideInstructions: function(url) {
    delete this._INSTURL;
    
    var div = $("#vgt-instructions");
    if (div)
        div.addClass("display-none");
},

showGetStarted: function() {
    var div = document.getElementById("vgt-get-started");
    if (div)
        this._showDialog(div, function() { $("#vgt-input-address").focus(); });
    else
        document.location.href = "index.do";
},

_showDialog: function(div, cb) {
    var w = div.parentNode.offsetWidth,
        h = div.parentNode.offsetHeight;
    div.style.width = w + "px";
    div.style.height = h + "px";
    div.firstChild.style.width = w + "px";
    div.firstChild.style.height = h + "px";

    var dialogDiv = this._firstChildElm(div, 1);

    if (dialogDiv) {
        // timeout because display:none prevents screen size from being determined...
        dialogDiv.style.left = "-1000px";
        window.setTimeout(function() {
            dialogDiv.style.position = "absolute";
            dialogDiv.style.left = Math.round((w - dialogDiv.offsetWidth)/2) + "px";
            dialogDiv.style.top = Math.max(0, Math.min(150, Math.round((h - dialogDiv.offsetHeight)/3))) + "px";
            $(dialogDiv).removeClass("hidden");
            if (cb)
                cb();
        }, 0);
    } else {
        // error
    }

    $(div).removeClass("display-none");
},

initMap: function(lon, lat) {
    if (this._yahoomap) return;
    var mapDiv = document.getElementById('map');
    if (!mapDiv) return;

    try {
        var map = new YMap(mapDiv);

        map.addTypeControl();
        map.addZoomLong();
//        map.addPanControl();

        // Set map type to either of: YAHOO_MAP_SAT, YAHOO_MAP_HYB, YAHOO_MAP_REG
        map.setMapType(YAHOO_MAP_REG);

        // Display the map centered on a geocoded location
        var centerPoint = new YGeoPoint(lat, lon);
        map.drawZoomAndCenter(centerPoint, 2);

        var newMarker = new YMarker(centerPoint);
        map.addOverlay(newMarker);

//        YEvent.Capture(map, EventsList.onEndGeoCode, this._onGeoDone);

        this._yahoomap = map;
    } catch (e) {
        // Hide map if it is not supported by Yahoo
        $(mapDiv).addClass("display-none");
    }
},

sendAddressErrorSuccess: function(objForm) {
    this.openAddressForm();
    var objLink = document.getElementById("vgt-address-error-msg");
    if (objLink)
        objLink.innerHTML = "Error report sent successfully.";
},

onAddressSubmit: function(objForm) {
    return true;
},

openAddressForm: function(objElm) {
    var div = $("#vgt-address-error-form");
    div.toggleClass("display-none");
},

hideGetStarted: function() {
    var div = $("#vgt-get-started");
    if (div)
        div.addClass("display-none");
},

onCompTargetOver: function(objTD) {
    if (this.CHOICE_COUNT > 2) {
        $(objTD).addClass("vgt-targeted");
        $(objTD).addClass("vgt-name-targeted");
    }
},

onCompTargetOut: function(objTD) {
    if (this.CHOICE_COUNT > 2) {
        $(objTD).removeClass("vgt-targeted");
        $(objTD).removeClass("vgt-name-targeted");
    }
},

onCompTargetClick: function(objTD, choiceId) {
    if (this.CHOICE_COUNT > 2) {
        this.addToComparison(choiceId);
        $.scrollTo($(".vgt-comparison .vgt-subheader"), 500);
    }
},

onSelTargetOver: function(objTD) {
    $(objTD).addClass("vgt-targeted");
    $("img", objTD).addClass("over");
},

onSelTargetOut: function(objTD) {
    $(objTD).removeClass("vgt-targeted");
    $("img", objTD).removeClass("over");
},

onSelTargetClick: function(objTD, choiceId) {
    $("form", objTD).submit();
},

onNavOver: function(objElm) {
    $(objElm).addClass("hover");
},

onNavOut: function(objElm) {
    $(objElm).removeClass("hover");
},

onNavClick: function(objElm) {
    var aTag = $("a", objElm)[0];
    if (aTag) {
        var url = aTag.getAttribute("href");

        if (this.getSelectedCount() == 0 && this.CHOICE_COUNT > 0 && this.INDEX == 0) {
            if (this.showInstructions(url))
                return;
        }
        
        document.location.href = url;
    }
}

    });
})(org.thevoterguide);

jQuery(document).ready(function() {
    var $ = org.thevoterguide.jQuery;
    $("form:not(.vgt-freesubmit):has(input:image, input:submit)", $("#vgt")).submit(function() {
        if (this._vgtsubmitted)
            return false;
        this._vgtsubmitted = true;

        $("input:image", this).addClass("vgt-submit-disabled");
        $("input:submit", this).addClass("vgt-submit-disabled");
    });
});
