/**********************************************************************
* Copyright 2009 Amblique :: www.amblique.com :: All Rights Reserved *
**********************************************************************/

// Array.indexOf(obj, [fromIndex]);
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

///
/// Global DOM.onReady event
///
/// DO NOT MODIFY THIS SECTION OF THE CODE
///
var CSS_CLASS_PREFIX = ".";
var TOP_PETS_CONTROL_LINK_CLASS = "a.tplink";
var QUESTION_LINK_SELECTOR = "span.question";
var BLUE_ICON_CSS = "transparent url(images/quiz-btn-blue.gif) no-repeat -1px 0";
var RED_ICON_CSS = "transparent url(images/quiz-btn.gif) no-repeat -1px 0";

// The following code are required to run on every page load AND ajax callback
function onDOMReady() {
    try { $('body').supersleight(); } catch (e) { }

    initialiseDefaultButtons(); // default buttons
    initialiseClearText(); // clear text
    initialisePetBadge(); // petbadge control
    initialiseHelpTooltips();
    $("abbr[class*=timeago]").timeago(); // timeago abbr elements
    $("a[href=#]").unbind("click").live("click", function(event) { return false; }); // click protection for anchors with href="#"
    $("a[rel*=overlay]").each(function(i) {
        if (!$(this).data("overlay")) {
            $(this).overlay({
                onBeforeLoad: function() {
                    this.getBackgroundImage().expose({ color: '#000' });
                },
                oneInstance: false,
                onClose: function() {
                    $.expose.close();
                }
            });
        }
    });
}

/* ga */
var GA_UA = "UA-3235635-10";
function GA_TrackPageview(pagename) {
    var pagename_prefix = "/ga/";
    var pagenames = {
        userlogin: "UserLoggedIn.htm",
        registercomplete: "RegisterComplete.htm",
        debatecomment: "DebateCommentSubmitted.htm",
        profilepicturechanged: "ProfilePictureChanged.htm",
        quizsubmitted: "QuizSubmitted.htm"
    };

    if (pagename in pagenames) {
        var relativeURL = pagename_prefix + pagenames[pagename];
        trace('google analytics tracking page: ' + relativeURL);
        try {
            if (typeof _gat != 'undefined') {
                trace('_gat found');
                var ga_pageTracker = _gat._getTracker(GA_UA);
                if (typeof ga_pageTracker != 'undefined') {
                    trace(ga_pageTracker);
                    ga_pageTracker._trackPageview(relativeURL);
                }
            }
        } catch (e) {
            trace('error tracking page in GA: ' + relativeURL);
        }
    }
}

/* dc floodlight */
function DCFL_Track(type) {
    // types == cat request parameter
    var types = {
        rego_step1: "advoc509",
        rego_step2: "regis854",
        rego_complete: "regis859",
        contact_complete: "conta558",
        invite_complete: "invit021",
        advocate_page: "bayer328"
    };
    var iframe_id = "dcfl_iframe";

    if (type in types) {
        var cat = types[type];
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        var url = "<iframe id='" + iframe_id + "' style='display:none;' src='http://fls.au.doubleclick.net/activityi;src=1733758;type=advoc540;cat=" + cat + ";ord=" + a + "?'></iframe>";

        // remove previous iframe
        if ($("#" + iframe_id).length > 0) {
            $("#" + iframe_id).remove();
        }
        
        if ($("body").length > 0) {
            $("body").prepend(url);
            trace(type);
        }
    }
}

var FEEDBACK_TYPE_VOTE = "vote";
var FEEDBACK_TYPE_REPORT = "report";
function showFeedback(message, type) {
    if (type == FEEDBACK_TYPE_VOTE) {
        var icon = "images/tick.gif";
        message = "<img src='" + icon + "' />&nbsp;" + message;
    }

    $.jGrowl(message, { position: 'center', closer: false, life: 2000 });
}

function clearText(event) {
    if (!event) return;
    if (event.type == "focus") {
        if (this.value == event.data.empty) {
            try { this.value = event.data.replacement; } catch (e) { }
        }
    }
    if (event.type == "blur") {
        if (this.value == '') {
            try { this.value = event.data.empty; } catch (e) { }
        }
    }
}

function initialiseClearText() {
    var CLEAR_TEXT_ATTRIBUTE = "cleartext";
    $("input[" + CLEAR_TEXT_ATTRIBUTE + "]").each(function(i) {
        var data = { replacement: '', empty: 'Search' };
        $(this).bind("focus blur", data, clearText);
    });
}

// Wire up textboxes to buttons
function initialiseDefaultButtons() {
    var DEFAULT_BUTTON_ATTRIBUTE = "default";
    $("input[" + DEFAULT_BUTTON_ATTRIBUTE + "]").each(function(i) {
        if (!$(this).data(DEFAULT_BUTTON_ATTRIBUTE)) {
            $(this).data(DEFAULT_BUTTON_ATTRIBUTE, true);
            $(this).bind("keypress", function(event) {
                if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
                    var target = $("#" + $(this).attr(DEFAULT_BUTTON_ATTRIBUTE));
                    if (target.length > 0) {
                        var tag = target[0].tagName;
                        if (/input/i.test(tag)) {
                            // THIS IS A TEMPORARY FIX TO SEARCH BUTTON
                            // i.e., when you try to login with invalid form values, then click on search button
                            // the form tries to re-validate the login controls rather than submitting a search query
                            if ($.data($("#form1")[0])) {
                                $("#form1").validate().resetForm();
                                $.removeData($("#form1")[0]);
                            }
                            target.trigger("click");
                        } else if (/a/i.test(tag)) {
                            var href = target.attr("href");
                            if (href.indexOf("javascript") >= 0) {
                                var bubble = target.triggerHandler("click");
                                if (bubble == true || typeof (bubble) == 'undefined') {
                                    eval(href);
                                }
                            }
                        }

                        return false;
                    }
                }
            });
        }
    });
}

// PetBadge tooltip
function initialisePetBadge() {
    var PB_RANK_CSS_CLASS = ".petBadge";
    var PB_RANK_DESC_CSS_CLASS = ".pb-rank-desc";

    $(PB_RANK_CSS_CLASS).each(function(i) {
        if ($(this).find(PB_RANK_DESC_CSS_CLASS).length > 0) {
            $(this).qtip({
                content: { text: $(this).find(PB_RANK_DESC_CSS_CLASS).html() },
                position: { corner: { target: "bottomRight", tooltip: "topLeft"} },
                style: { width: 200, padding: 5, background: '#fff', color: 'black', textAlign: 'center', border: { width: 7, radius: 5, color: '#ccc' }, tip: 'topLeft', name: 'dark' }
            });
        }
    });
}

function initialiseHelpTooltips() {
    var TOOLTIP_CSS_CLASS = ".help-tooltip";
    var TOOLTIP_TEXT_CSS_CLASS = TOOLTIP_CSS_CLASS + "-text";
    $(TOOLTIP_CSS_CLASS).each(function(i) {
        if ($(this).siblings(TOOLTIP_TEXT_CSS_CLASS).length > 0) {
            var targetPosition = $($(this).siblings(TOOLTIP_TEXT_CSS_CLASS)[0]).attr('position');
            var tooltipPosition = targetPosition == "leftMiddle" ? "rightMiddle" : "leftMiddle";
            $(this).qtip({
                content: { text: $(this).siblings(TOOLTIP_TEXT_CSS_CLASS).html() },
                position: { corner: { target: targetPosition, tooltip: tooltipPosition} },
                style: { width: 200, padding: 5, background: '#fff', color: 'black', textAlign: 'left', border: { width: 7, radius: 5, color: '#f1861c' }, tip: tooltipPosition, name: 'dark' }
            });
        }
    });

    $("a.hasTooltip").each(function(i) {
        var tooltipText = $(this).attr("message");
        if (tooltipText.length > 0) {
            $(this).qtip({
                content: { text: tooltipText },
                position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle'} },
                style: { width: 200, padding: 5, background: '#fff', color: 'black', textAlign: 'left', border: { width: 7, radius: 5, color: '#f1861c' }, tip: 'leftMiddle', name: 'dark' }
            });
        }
    });
}

function trace(message) {
//    var page = window.location; var hasConsole = false;
//    try { if (typeof (console) != "undefined") hasConsole = true; } catch (e) { }
//    if (hasConsole) { console.log(message); }
}

function reloadPage() {
    try {
        window.location.reload();
    } catch (e) {
        window.location.href = window.location.href;
    }
}

function rotateTopPets() {
    $(TOP_PETS_CONTROL_LINK_CLASS).each(function(i) {
        var toShow = $(this).attr("rel");
        if ($(CSS_CLASS_PREFIX + toShow).is(":hidden")) {
            $(this).trigger("click");
        }
    });
}

function AutoMapZoom(page, stateName) {
    if (typeof page == 'string' && typeof stateName == 'string') {
        window.location.href = page + '&state=' + stateName;
    }
}

$(function() {
    // debug: cookie
    trace(document.cookie);
    if ($('input[id*=hfLSID]').length > 0) trace($('input[id*=hfLSID]')[0].value);

    onDOMReady();

    // Top pets control
    var FADE_SPEED = 100;
    $(TOP_PETS_CONTROL_LINK_CLASS).live("click", function(event) {
        var toShow = $(this).attr("rel");
        var ICON_CSS = toShow == "tp-cats" ? RED_ICON_CSS : BLUE_ICON_CSS;
        $(TOP_PETS_CONTROL_LINK_CLASS).each(function(i) {
            var rel = $(this).attr("rel");
            if (rel != toShow)
                $(CSS_CLASS_PREFIX + rel).fadeOut(FADE_SPEED, function() {
                    $(CSS_CLASS_PREFIX + toShow).fadeIn(FADE_SPEED);
                    $(QUESTION_LINK_SELECTOR).css("background", ICON_CSS);
                });
        });
    });

    // start the timer for top pets control
    if ($(TOP_PETS_CONTROL_LINK_CLASS).length > 0) {
        $(window).everyTime(15000, "toppets", rotateTopPets);
    }
});

jQuery.validator.messages.required = "";
