var timeoutId = 0;
var tries = 0;

// Create IE + others compatible event handler
function subscribe_postmessage(win, func) {
    // this hooks up the postMessage with either the main window, or iframe
    var eventMethod = win.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = win[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

    eventer(messageEvent, func, false);
}

function getBrands() {
    // we've tried 5 times, time to give up
    if (tries == 5) {
        clearInterval(timeoutId);
    }
    // tell the child we want them to check for brands
    var win = $('#messageFrame')[0].contentWindow;
    win.postMessage(nimbus_url, nimbus_url);
    tries = tries+1;
}

function displayMessage (evt) {
    clearInterval(timeoutId);
    if (evt.data.length > 0) {
        // They have admin access to the brand they are viewing
        if (current_brand == evt.data) {
            $('.nb-admin-link').fadeIn();
        }
    }
}

function sendMessage(e) {

    $.getJSON(e.data + '_getbrands_json', function(data) {
        for (var index=0; index < data.length; index++) {
            parent.postMessage(data[index].abbr, e.origin);
        }
    });
}

$(document).ready(function() {
    if($('#messageFrame').length == 1) {
        // have parent wait for child to send a message
        subscribe_postmessage(window, displayMessage);

        // keep trying until we recieve a message back
        timeoutId = setInterval("getBrands()", 500);
    }
});


