/**
 * This file depends on the jQuery library version >= 1.2.6
 *
 * @author  Ryan Timmons
 * @date    05 September 2008
 */

/// 
/// Hides the search form submit button.  I'm not sure if we should be
/// hiding or how we want to handle submitting that data: forms will
/// submit when the user hits enter, but do we trust users to know that?
/// 
var hide_search_link = function()
{
    $('#search input[type="submit"]').hide();
};



/// 
/// In all, this amounts to taking a DOM structure like
/// 
///     <ul class="selector">
///         <li><img src="1" /> [Other Content 1]</li>
///         <li><img src="2" /> [Other Content 2]</li>
///         <li><img src="3" /> [Other Content 3]</li>
///     </ul>
/// 
/// and replacing it with a DOM structure like
/// 
///     <ul class="selector final">
///         <li class="selector_0"><img src="1" /></li>
///         <li class="selector_1"><img src="2" /></li>
///         <li class="selector_2"><img src="3" /></li>
///     </ul>
///     <ul class="selector">
///         <li class="selctor_0">[Other Content 1]</li>
///         <li class="selctor_1">[Other Content 2]</li>
///         <li class="selctor_2">[Other Content 3]</li>
///     </ul>
/// 
/// This is used on the networking.php page to make the 
/// clickable boxen.
///
var make_selectoruls_image_list = function()
{
    $('ul.selector').each(function(){
        // create the new ul to insert above this one
        var ul = $(document.createElement('ul'));
        // make it like
        //
        //     <ul class="selector final">
        //
        $(ul).addClass('selector').addClass('final');
        
        var classes = []; // see (*1*), below

        // find all the images inside our ul. We'll duplicate the image and
        // wrap it in a new `<li>` and put it inside our newly-created `ul`
        // element above. We'll then remove the original image from the DOM
        // and hide its parent `<li>`.
        //
        // And when clicking on an image in the `<ul class="selector final">`,
        // we make the respective `<li>` in the *other* `<ul>` visible and
        // hide the rest. This is why we have our `classes` array:  so we can    (*1*)
        // keep track of which `<li>`s we need to hide and which we don't.
        //
        //
        // Note that the below assumes that there is only one image inside a
        // given `<li>` for the original `<ul class="selector">`.  This code
        // could pretty easily be modified to handle that case, but this is
        // rapid-prototyping, man :).
        //
        // TODO: allow for other images inside the items
        // 
        $( 'img', this ).each(function( jj ){
            
            // throughout let's say that `this` is
            //
            //     <img src="1" />
            // 
            // in HTML form.  `jj` is the index of the image.  I'll use 0.
            
            
            // wrap the image in a new `<li>` element and select
            // it.  `li`, in HTML form, will look like
            //
            //    <li><img src="1" /></li>
            // 
            // once this executes since `this` is our image.
            //
            var li = $(this).wrap( document.createElement('li') )
                          // now select our outer elt
                          .parent();
            
            // Stop.  It's reflection time.
            //
            // Now our DOM structure is like
            //
            //    <ul class="selector final">
            //        <li><li><img src="1" />[Other Content 1]</li></li>
            //        <li><img src="2" />[Other Content 2]</li>
            //        ...
            //    </ul>
            //
            // (Notice the `<li>` inside the other `<li>`.)

            
            // Aggregate our classes
            //
            var classname = 'selector_' + jj;  // #=> selector_0
            classes.push( classname );
            
            // Attach our class to the  'outer' `<li>`
            //
            li.parent().addClass( classname );
            
            // Now our DOM structure is like
            //
            //    <ul class="selector final">
            //        <li class="selector_0">
            //            <li><img src="1" />[Other Content 1]</li></li>
            //        <li><img src="2" />[Other Content 2]</li>
            //        ...
            //    </ul>
            //
            
            // `newelt` is what we're going to be adding to our new 
            // `<ul class="selector final">`.  It looks like
            //
            //    <li class="selector_0"><img src="1" /></li>
            //
            // (Notice that it's *not* the bits with the `[Content 1]`.)
            //
            var newelt  = li
                .addClass( classname )
                .clone();
            
            // Attach our event to `newelt`...
            newelt.click(function(){
                toggle_lis( this, classes );
            });
            
            // uncommont tomake the newelt have the hand cursor when
            // moused-over:
            //
            //     newelt.css('cursor','pointer');
            //
            
            // ...and add it to our `ul`
            $( ul ).append( newelt );
            
            // and remove it from the DOM (this would result in
            // it being 'garbage-collcted', but we actually have a clone of
            // it in the form of `newelt` inside our `ul`).
            $(this).parent().remove();
        });
        
        // We're done adding classes and modifying the DOM for our inner
        // `<ul class="selector">`.  Now we need to hide it:
        //
        $.each(classes,function(){
            // Don't grab the outer `<ul class="final">`
            $('ul.selector:not(.final) .' + this).hide();
        });
        
        // back to the `<ul>`:
        insert_selector_elements( this, ul );
        
        
        var initial = $('li#initially_visible').show();
        move_arrow_below( 
            ( $('li.' + initial.attr('class').split(' ') || [''] )[0]) 
        );
    });
};

var randomize_tier2_banner = function()
{
    var imgLetter = String.fromCharCode(97 + Math.round(Math.random() * 5));
    var src       = "http://www.purenetworks.com/images/Tier2_" + imgLetter + '.jpg';
    $('#tier2img').attr('src', src);
}

var insert_selector_elements = function( ul_context, new_ul_dom_elt )
{
    $( ul_context ).before( new_ul_dom_elt )
    var arrow = $(document.createElement('img'))
                    // TODO: modify this image's source to be more portable
                    .attr('src','images/layout/selection_arrow.gif')
                    .attr('id','selector_arrow_img');

    var struct = '<div><div><div></div></div></div>';
    $( 'div div', $(new_ul_dom_elt).after(struct).next('div') )
        .append( arrow )
        .append( '<br />' ) // we're going to be making the arrow have
                            // position = absolute, so there needs to be
                            // something inside the div or it'll lose its bg
        // add all our necessary classes from the inside-out:
        .addClass('selectorinner')
        .parent()
        .addClass('selectorright')
        .parent()
        .addClass('selectorleft')
    ;
};

var move_arrow_below = function( li_context )
{
    var box    = $( 'img', li_context );
    var offset = box.offset();
    var width  = box.width();
    var arrow  = $('#selector_arrow_img');

    arrow.css({
        position: 'absolute',
        left: offset.left + Math.floor( width / 2 )
    });

};


var toggle_lis = function( context, classes )
{
    // it might have more than one class, so split on spaces and grab the first
    var parent_class = 
        ( $(context).attr('class').split(/\s+/) || [''] )[0];
    
    move_arrow_below( context );
    $( 'ul.selector li.' + parent_class ).show();
    $( 'ul.selector:not(.final) > li:not(.' + parent_class + ')').hide();
};


var build_sections_bar = function()
{
    var ul = $( document.createElement('ul') );
    $('ul.sections').each(function(){
        var sections = [];
        $(this).children('li').each(function(){
            sections.push( $(this).attr('title') );
            var classn = sections.length - 1;
            $(this).addClass( 'section_' + classn )
                   .hide()
            ;
            var link = $( document.createElement('a') )
                   .attr( 'href','section_' + classn )
                   .html( sections[classn] )
                   .click(function(){
                       return toggle_sections( this, sections );
                   });
            ;
            var li = $( document.createElement('li') );
            li.append( link );
            ul.append( li );
        })
        ;
        var wrapper   = $( document.createElement('div') )
                            .attr('id','switcherwrapper');
        var switcher  = $( document.createElement('div') )
                            .attr('id','switcher');
        var to_insert = wrapper.append( switcher );
        switcher.append( ul );
        $(this).before( to_insert );
        return false; // prevent further `each` matching
    }); // each ul.sections
};

var toggle_sections = function( link_context, sections )
{
    $('li.section_visible').removeClass('section_visible');
    add_visible_corners(
        $(link_context).parent('li').addClass('section_visible')
    );
    var class_to_show = $(link_context).attr('href').split(/\s+/)[0];
    $('li.'+class_to_show).show();
    
    $.each( sections, function(k,v){
        if ( $.trim(v) != $.trim($(link_context).html()) )
            $('li.section_' + k ).hide();
    });
    return false;
};

var lft_visible_corner = new Image();
lft_visible_corner.src = 'http://www.purenetworks.com/images/layout/switcher_left.gif';
var rt_visible_corner  = new Image();
rt_visible_corner.src  = 'http://www.purenetworks.com/images/layout/switcher_right.gif';

//
// TODO:  this is super ugly but strangely effective...
//
var add_visible_corners = function( li_context )
{
    var lft_img  = $( lft_visible_corner ).css({
        position: 'absolute',
        left: 0,
        top: 0
    });
    
    var rt_img = $( rt_visible_corner ).css({
        position: 'absolute',
        right: 0,
        top: 0
    });
    
    $(li_context).prepend( lft_img )
                 .append(  rt_img  );
};

var add_nav_dividers = function()
{
    // var lis = $('div#nav > ul > li'),
    //     len = lis.length;
    // 
    // $(lis).each(function(ind){
    //     if ( ind != len - 1 )
    //         $(this).append('<img src="http://www.purenetworks.com/images/layout/Nav_Divider.gif"/>');
    // });
};

var initial_tab_click = function()
{
    // a bit of a hack:  call the `click` lambda on our link that 
    // has href=(the same class as the li with id=initially_visible)
    // TODO: do this better :)
    // Click twice because FF3 doesn't really react well or at all to the first one'
    //
    $('a[href='+$("li#initially_visible").attr('class')+']').click();
    $('a[href='+$("li#initially_visible").attr('class')+']').click();
};

var openWindowDownload = function(sUrl)
{
    window.open( sUrl,
                 "downloadWindow",
                    "width=640,"
                 +  "height=400,"
                 +  "scrollbars=yes,"
                 +  "resizable=no,"
                 +  "status=no,"
                 +  "toolbar=no,"
                 +  "menubar=no" ).focus();
};

$(document).ready(function(){
    add_nav_dividers();
    hide_search_link();
    randomize_tier2_banner();
    make_selectoruls_image_list();
    build_sections_bar();
    setTimeout( initial_tab_click, 0 );
});