// page.js
// for www.irwelldesign.co.uk

$(function() {
    var static_prefix = '/static/';

    // fix for Firefox 3.x, which mysteriously inserts a </a> tag sometimes
    // in the home page
    // (probably related to http://stackoverflow.com/questions/2191029/firefox-rendering-gone-wrong-see-something-really-weird)
    $('#homeRhs>a').each(function() {
	if ($(this).find('div').length == 0) {
	    // instead of a>div, we find a followed by div.  rewrite DOM
	    var divObj = $(this).next();
	    divObj.detach();
	    $(this).append(divObj);

	    // h1>span shouldn't have an a tag inside.  if we find one, replace with its contents
	    var aObj = divObj.find('h1>span>a');
	    if (aObj.length > 0) {
		divObj.find('h1>span').append(aObj.html());
		aObj.remove();
	    }
	}
    });

    // replace birds div's background with plain blue bar
    $('#birds').css('background-image', 'url(' + static_prefix + 'images/bluebarbg.png)');

    // create birds animation
    for (var i = 1; i <= 3; i++)
	$('#birds').append('<img src="' + static_prefix + 'images/bluebar' + i + '.png" width="1920" height="146">');    
    $('#birds').cycle({fx: 'fade', speed: 1000, timeout: 1});

    // flow text around any images
    $('.wrappedImg').wrapIrregular();

    // animations for non-current submenus
    $('.navSubmenu').mouseenter(function() {
	// cancel mouseleave timer, if any
	var timerId = $(this).data('timerId');
	if (timerId != undefined) {
	    clearTimeout(timerId);
	    $(this).data('timerId', undefined);
	}

	// note: we track the state ourselves to allow us to act as
	// though animations were instantaneous
	var state = $(this).data('state');
	if (state == undefined || state == 'hidden') {
	    $(this).find('ul').slideDown('slow');
	    $(this).data('state', 'visible');
	}
    });

    $('.navSubmenu').mouseleave(function() {
	var tmp = $(this);
	
	// debounce with a 1-second delay
	var timerId = setTimeout(function() {
	    // hide submenu
	    if (!tmp.find('ul').is(':hidden'))
		tmp.find('ul').slideUp();

	    // mark state as hidden (treating the anim as instantaneous)
	    tmp.data('state', 'hidden');

	    // clear active timer
	    tmp.data('timerId', undefined);
	}, 1000);

	// record the currently-active timer
	tmp.data('timerId', timerId);
    });

    // ------------------------------------------------------------------------
    // home page animations
    // ------------------------------------------------------------------------
    var homeAnimObj = null;  // object which is currently slideDown()ing
    var homeCrntObj = null;  // object over which mouse is hovering

    // mark the active menu item as visible
    function onEnterHomeMenu() {
	homeCrntObj = this;

	if ($(this).hasClass('homeMenuInactive') && homeAnimObj == null) {
	    // switch to homeMenuActive class, but keep display: none
	    $(this).removeClass('homeMenuInactive');
	    $(this).addClass('homeMenuActive');
	    $(this).find('div div').css('display', 'none');
	    
	    // slide down, blocking further slideDown()s while the
	    // animation is in progress.
	    $(this).find('div div').slideDown('slow', function() {
 		homeAnimObj = null;
	    });
	    homeAnimObj = this;

	    var originalObj = this;

	    // hide previously active menu items
	    $('.homeMenuActive').each(function() {
		if (this != originalObj) {
		    var aObj = $(this);
		    $(this).find('div div').slideUp('slow', function() {
			aObj.removeClass('homeMenuActive');
			aObj.addClass('homeMenuInactive');

			// if the pointer has drifted to another object, we'd
			// better show that object
			if (homeCrntObj != null && homeCrntObj != aObj)
			    onEnterHomeMenu.call(homeCrntObj);
		    });
		}
	    });
	}
    }

    // set up handlers
    $('.homeMenuInactive,.homeMenuActive').mouseenter(onEnterHomeMenu);
    $('.homeMenuInactive,.homeMenuActive').mouseleave(function() {
	homeCrntObj = null;
    });


    // ------------------------------------------------------------------------
    // contact us form
    // ------------------------------------------------------------------------
    $('form').submit(function() {
	if ($('#frmEmail').val().length == 0 &&
	    $('#frmPhone').val().length == 0) {
	    alert('Please enter either an email address or phone number.');
	    return false;
	}
    });

    function layoutPage() {
	// adjust layout for page width
	var width = $(window).width();

	// clamp
	var max_width = 1400;
	var min_width = 790;

	if (width > max_width)
	    width = max_width;
	if (width < min_width)
	    width = min_width;

	// total margins either side of the page
	var margin = 100;
	if (width - min_width < margin)
	    margin = width - min_width;

	width -= margin;

	$('#headerContainer,#container').css('width', width);

	function adjustDimen(selector, attrib, min, max) {
	    var frac = (width - min_width) / (max_width - min_width);
	    var value = min + frac * (max - min);
	    $(selector).css(attrib, value);
	}

	// add a bit of white space when we can afford to do so
	adjustDimen('#layoutCol1', 'padding-right', 20, 60);
	adjustDimen('#content h1 span,.exampleBox h1 span', 'padding-left', 20, 40);
	adjustDimen('#content h1 span,.exampleBox h1 span', 'padding-right', 20, 40);
	adjustDimen('#contentBody', 'padding-left', 20, 40);
	adjustDimen('#contentBody', 'padding-right', 20, 40);
	adjustDimen('.exampleBox .lhsCol,.exampleBox .bothCol', 'padding-left', 20, 40);
	adjustDimen('.exampleBox .lhsCol', 'padding-right', 20, 40);
	adjustDimen('.exampleBox .rhsCol,.exampleBox .bothCol', 'padding-right', 20, 40);
	adjustDimen('#homeRhs .lhsCol', 'padding-left', 20, 40);
	adjustDimen('#homeRhs .rhsCol', 'padding-right', 20, 40);
	adjustDimen('.homeMenuActive h1 span,.homeMenuInactive h1 span', 'padding-left', 20, 40);
	adjustDimen('.homeMenuActive h1 span,.homeMenuInactive h1 span', 'padding-right', 20, 40);
    }

    // perform initial layout
    layoutPage();

    // layout page on resize, with debouncing
    var pageTimerId = null;
    $(window).resize(function() {
	// cancel current timeout, if any
	if (pageTimerId != null)
	    clearTimeout(pageTimerId);

	// and schedule another one
	pageTimerId = setTimeout(function() {
	    layoutPage();
	    pageTimerId = null;
	}, 100);
    });
});
