var $ = _$ = jQuery;

function apaslt09_aligned_images() {
    var maxPhotos = _$('#body div.photoRight, #body div.photoLeft').length - 1;
    _$('#body div.photoRight, #body div.photoLeft').each(function(i) {
        var thisClass = _$(this).attr('class');

        // Check for image
        if (_$(this).find('img').length) {
            _$(this).show();
        }
        else {
            return;
        }

        // Fixed width
        if (_$(this).find('img').attr('width') > 0) {
            var thisWidth = _$(this).find('img').attr('width');
        }
        else {
            var thisWidth = _$(this).find('img').show().width();
        }
        _$(this).css('width', thisWidth + 'px');

        // Add float
        if (thisClass.indexOf('Right') != -1) {
            _$(this).addClass('photoRightFloat');
        }
        else {
            _$(this).addClass('photoLeftFloat');
        }

        // Clear
        if (i == maxPhotos) {
            _$(this).parent().append('<div class="clear"></div>');
        }
    });
}

function apaslt09_inline_labels(formObject) {
	var _$form = _$(formObject);
	_$('input:text, textarea', _$form).each(function() {
		var itemLabel = _$('label', _$(this).parents('div.form-item')).text();
		_$(this).focus(function() {
			if( _$(this).val() == itemLabel ) {
				_$(this).val('');
			}
		}).blur(function() {
			if( _$(this).val() == '' ) {
				_$(this).val(itemLabel);
			}
		});
		_$(this).trigger('blur');
	});
	_$('select', _$form).each(function() {
		var selectLabel = _$('label', _$(this).parents('div.form-item')).text();
		_$(this).prepend('<option value="" selected="selected">' + selectLabel + '</option>');
	});
}

function apaslt09_render_sidebar(sectionName, ulClass) {
	// Display sub-menu
	_$('ul#nav-' + sectionName).show();

	// Raw HTML
	var linksHtml = _$('ul#nav-' + sectionName).html();
	var titleHtml = _$('ul#nav-' + sectionName).parent().find('a.top-level');
	var titleClass = _$('ul#nav-' + sectionName).parent().attr('class');
	
	// Duplicate active section
	_$('#content div.sub-area').clone().prependTo('#sidebar').attr('id', 'sub-content-first');
	_$('#sub-content-first div.sub-content').empty().html('<ul><li id="sub-content-first-li" class="' + titleClass + '"></li></ul>');
	_$('#sub-content-first-li').html('<ul>' + linksHtml + '</ul>').prepend(titleHtml);
	
	// Remove sub-tiers if no children
	if( _$('#sub-content-first-li > ul > li').length == 0) {
	    _$('#sub-content-first-li > ul').remove();
	}

	// Remove original
	_$('ul#nav-' + sectionName).parent().remove();
	
	// Add body class
	//if(ulClass != 'thirdOrBelow') {
	_$('body').addClass('section-' + sectionName);
	//}
}

function apaslt09_detect_sidebar() {
    /* Global variables */
    var activeUri = document.location.href.split(".net")[1].split("#")[0];
	
    /* Prevent third-tier pages from adding body class */
    _$('#sidebar li.second-tier > ul ul').addClass('thirdOrBelow');

    /* Detect active section from sub-menu */
    _$('#sidebar li.second-tier > ul').hide();
    _$('#sidebar li.second-tier > ul > li a').each(function() {
        var thisUri = _$(this).attr('href').split(".net")[1];
        if (thisUri == activeUri) {
            // Section found! Set up variables
            var sectionName = _$(this).parents('ul[@id]').attr('id').replace('nav-', '');
			
			// Add body class?
			var ulClass = _$(this).parents('li').parents('ul').attr('class');

            apaslt09_render_sidebar(sectionName, ulClass);
        }
    });

    /* Detect active section from top-level links */
    _$('#sidebar .sub-content a.top-level').each(function() {
        var thisUri = _$(this).attr('href');
        if (thisUri == activeUri) {
            // Section found!
            var sectionName = _$(this).parent().find('ul[@id]').attr('id').replace('nav-', '');
			
			// Add body class?
			var ulClass = 'top-level';

            apaslt09_render_sidebar(sectionName, ulClass);
        }
    });

    /* Detect sub-categories */
    _$('#sidebar ul ul ul > li > a').each(function() {
    if (_$(this).text() == "Software" || _$(this).text() == "Hardware") {
            _$(this).after('<span class="subcat">' + _$(this).text() + '</span>').remove();
        }
    });

    /* Show menu */
    _$('#sidebar div.sub-area').show();

    /* Adjust last-child */
    _$('#sidebar .sub-content:last > ul > li:last-child').addClass('last-child');
}

function apaslt09_jnice_buttons(object) {
	var buttonHref = _$(object).attr('href');
	var buttonText = _$(object).text();
	var buttonClass = (_$(object).is('.button-small')) ? ' small' : '';
	var html = _$('<button class="jNiceButton' + buttonClass + '"><span><span>' + buttonText + '</span></span></button>').click(function() {
		window.location.href = buttonHref;
		return false;
	});
	_$(object).after(html);
	_$(object).remove();
}

function apaslt09_ready() {
	// Sidebar
    apaslt09_detect_sidebar();
	
	// Dynamic Buttons
	_$('#body a.button').each(function() {
		apaslt09_jnice_buttons(_$(this));
	});
	
	// News
	_$('#newsList table.ArticleList tr td').each(function() {
		// Hide description if none
		if( _$('.description span.text', this).text().replace(/^\s+|\s+_$/g, '') == "") {
			_$('.description', this).hide();
		}
		// Title as link
		if( _$('.readMore a', this).length ) {
			var editLink = _$('.title h3 a', this);
			_$('.title h3', this).html('<a href="' + _$('.readMore a', this).attr('href') + '">' + _$('.title h3', this).text() + '</a>').prepend(editLink);
		}
	});
	
	// Breadcrumbs
	if( _$('#body div.breadcrumbs').length ) {
	    _$('#body div.breadcrumbs a').each(function() {
	        if( _$(this).text() == "Hardware" || _$(this).text() == "Software" ) {
	            _$(this).remove();
	        }
	    });
	    var breadcrumbsHtml = _$('#body div.breadcrumbs').html().replace('&nbsp;&gt;&nbsp;&nbsp;&gt;&nbsp;', '&nbsp;&gt;&nbsp;');
	    _$('#body div.breadcrumbs').html(breadcrumbsHtml);
	}
	
	// Aligned Photos
	apaslt09_aligned_images();
	
	// Table of Photos
	_$('#body table.photoAndDescription').find('td img').parents('td').addClass('image');
	
	// Repositioned Lists
	_$('#body .Normal ul').each(function() {
		_$(this).prev('h3, h2').addClass('ul-offset');
	});

    // Anchor Links
    if (_$('#content div.anchorSections').length) {
        var numAnchors = _$('#content div.anchorSections h2').not('h2.noAnchor').length;
        var backLinkHtml = '<a class="backLink" href="#anchorTop">Back to top</a>';
        var anchorLinksHtml = "";
        _$('#content h1.pageTitle').after('<div class="anchorLinks"></div><div class="clear"></div>').attr('id', 'anchorTop');
        _$('#content div.anchorSections h2').not('h2.noAnchor').each(function(i) {
			if( _$('a.anchor', this).attr('name') ) {
				var anchorName = _$('a.anchor', this).attr('name');
			}
			else {
				var anchorName = 'dynAnchor' + i;
			}
            anchorLinksHtml += '<span class="nowrap"><a href="#' + anchorName + '">' + _$(this).text() + '</a>';
            if ((i + 1) != numAnchors) {
                anchorLinksHtml += "&nbsp;&nbsp;|&nbsp;&nbsp;";
            }
			anchorLinksHtml += '</span>';
            _$(this).html('<a class="anchor" name="' + anchorName + '">' + _$(this).text() + '</a><div class="clear"></div>');
            
            // Back to top
            var inext = i+1;
            var ilength = _$('#content div.anchorSections h2').length;
            if(inext == ilength) {
                _$('#content div.anchorSections h2:first').parent().append(backLinkHtml);
            }
            else {
                _$('#content div.anchorSections h2:eq(' + inext + ')').before(backLinkHtml);
            }
        });
        _$('#content div.anchorLinks').html(anchorLinksHtml);
    }

    // Callouts
    _$('#body div.callout h3:first-child').addClass('first-child');
    _$('#body div.callout p:last-child').addClass('last-child');
    
    // Blockquotes
    _$('#body ul').next('h3').css('margin-top','0');
    _$('#body blockquote ul:last-child').css('padding-bottom','0');
	
	// External links
	_$("#body a[@href^=http]").not("[@href*='sl-tech.net']").not("[@href*='sltech.uppercasedev']").each(function() {
		_$(this).addClass('extLink').attr('target','_blank');
		if( _$(this).find('img').length ) {
			_$(this).removeClass('extLink');
		}
	});
	

    // Edit mode
    if (_$('#dnn_ControlPanel table').length) {
        if (_$('#dnn_ControlPanel span.SubHead span[@resourcekey="ModeEdit"] input').attr('checked')) {
            _$('#body').addClass('editMode');
        }
        else if (_$('#dnn_ControlPanel span.SubHead span[@resourcekey="ModeEdit"] input').attr('checked')) {
            _$('#body').addClass('designMode');
        }
		else {
			_$('body').addClass('nonViewMode');
		}
    }
}

_$(document).ready(function() {
    apaslt09_ready();
});
