function if_fadeSetup(mainID, showFirst) {
    var main = if_getFromID(mainID);
    main.addClass('if_main');
    main.children().addClass('if_fadeMe');

    // Adjust zIndex to prevent content from being hidden or unselectable
    main.children().each(function(n) {
        var currentZ = $(this).css("zIndex");
        var newZ = (currentZ + main.children().size()) - n;
        $(this).css("zIndex", newZ);
    });
    
    // Analyse and correct the showFirst input, then fade to it.
    if_fade(mainID, showFirst);

    // Returning the ID allows for easy calling of the controller and/or timer (coming soon?)
    return mainID;

}

function if_fade(mainID, next) {
    // Get the proper elements (main and container)
    var main = if_getFromID(mainID);
    
    // Normalize var next. Set to 0 if it is not a number or if it is larger than the number of fading elements.
    next = Number(next);
    if (!next || (next + 1) > main.children().size() || isNaN(next)) {
        next = 0;
    }
    // Set zIndex and add/remove classes
    var oldE = main.children(".if_100opacity");
    oldE.css("zIndex", (oldE.css("zIndex") - main.children().size()));
    oldE.removeClass("if_100opacity");
    var nextE = main.children().eq(next);
    nextE.css("zIndex", Number(nextE.css("zIndex")) + Number(main.children().size()));
    nextE.addClass("if_100opacity"); //.css("zIndex", nextE.css("zIndex") + main.children().size());

    
}

// Setup the controller
function if_fadeController(mainID, controllerID) {

    // Get the main, controller, and container elements and put them each in a wrapped set.
    var main = if_getFromID(mainID);
    var controller = if_getFromID(controllerID);

    // Set up the controller by binding a click event to each one
    controller.children().each(function() {
        var i = $(this).index();
        $(this).bind("click",{"mainID": mainID, "next": i}, if_fade_controller);
    });
}

function if_fade_controller(event) {
    // send the proper data to the if_slide function
    if_fade(event.data.mainID, event.data.next);

    // Hack to hide the URL bar in the iPhone / iPod Touch / iPad etc...

}

function if_fadeTimer(mainID, ms) {
    // Get the main and container elements and put them each in a wrapped set.
    var main = if_getFromID(mainID);
    window.setInterval(function() {if_fade(mainID, main.children().index(main.children('.if_100opacity')) + 1)}, ms);
}



// Returns the element in a jQuery wrapped set. Input is the ID (with or without the #) of the element
function if_getFromID(elementID) {
 //    Normalize the ID and put it in a wrapped set.
    if (elementID.substring(0,1) != '#') {
        elementID = '#' + elementID;
    }
    return $(elementID);
}

// Returns the ID of the element (without? the #)
function if_getID(element) {
    return element.attr("id");
}

