var slideindex = 0;
var hovering = false;
var slidetimeout = 7500;

function str_replace (search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}



function hook_dot_nav() {
	$('#dotnav li a').click(function() {
		
		$('#dotnav li a').unbind('click');
		
		if( !$(this).hasClass('active') ) {
			
			// handle the short circuit
			$('#dotnav li a').removeClass('active');
			$(this).addClass('active');
			
			// snag the clicked index
			var clicked = $('#dotnav li').index( $(this).parent() );
			
			if(hovering==true) {
				slideindex = clicked - 1;
			}

			// set all alt attributes to inactive
			$('#dotnav li a img').attr('alt','Inactive photo');

			// set the proper alt attribute for active
			$(this).find('img').attr('alt','Active photo');

			// set all the dots to inactive
			$('#dotnav li a img').each(function() {
				$(this).attr( 'src', str_replace( 'dot-active', 'dot-inactive', $(this).attr('src') ) );
			});

			// set just the clicked dot to be active
			$(this).find('img').attr( 'src', str_replace( 'dot-inactive', 'dot-active', $(this).find('img').attr('src') ) );

			// fade to the proper image
			$('#imageholder').fadeTo('fast', 0.01, function() {
				for (var i=0; i < photos.length; i++) {
					$('#imageholder').removeClass('slide_' + i);
				}
				$('#imageholder').addClass('slide_' + clicked);
				$('#imageholder').fadeTo('slow', 1, function() {
					hook_dot_nav();
				});
			});
			
		} else {
			hook_dot_nav();
		}
		
		return false;
	});
}



function hook_toggle() {
	$('#toggle a').click(function() {

		// hide our toggle for now
		$('#toggle a').fadeTo('fast', 0.01, function() {
			
			// check to see if we're expanding or contracting
			if( $('#nav').hasClass('expanded') ) {
				logotop = "18px";
				navtop = "-320px";
				targetopacity = 0.01;
			} else {
				logotop = "50px";
				navtop = "0";
				targetopacity = 1;
			}
			
			// hide (or show) the headings and labels
			if( $('.ie').length == 0 ) {
				$('#sitenav').fadeTo('fast', targetopacity);
			} else {
				if( targetopacity == 1 ) {
					$('#sitenav').css('visibility', 'visible');
				} else {
					$('#sitenav').css('visibility', 'hidden');
				}
				
			}
			
			// fix the top padding on the logo
			$('#linkhome').animate(
			{ paddingTop: "" + logotop + "" }, {
				duration: 700,
				easing: 'easeInOutQuad',
				complete: function() {
						$('#toggle a').fadeTo('fast', 1);
					}
			});
			
			// fix the position of the nav
			$('#nav').animate(
			{ top: "" + navtop + "" }, {
				duration: 700,
				easing: 'easeInOutQuad',
				complete: function() {
						$('#toggle a').fadeTo('fast', 1);
					}
			});
			
			
			// class cleanup
			$('#nav').toggleClass('expanded');
			$('#nav').toggleClass('contracted');

		});

		return false;
	});
}


function prep_forms() {
	
	// let's hide the labels and move them inside the inputs
	$('.form .textfield, .form .textarea').not('.alt').find('label').css('visibility', 'hidden');
	$('.textfield').not('.alt').each(function() {
		$(this).find('input').attr( 'value', $(this).find('label').text() );
	});
	$('.textarea').each(function() {
		$(this).find('textarea').val( $(this).find('label').text() );
	});
	
	// let's clear out the value when clicked
	$('.textfield input').not('.alt').focus(function() {
		if( $(this).attr('value')==$(this).parent().find('label').text() ) {
			$(this).attr('value', '');
		}
	});
	$('.textfield input').not('.alt').blur(function() {
		if( $(this).attr('value')=='' ) {
			$(this).attr( 'value', $(this).parent().find('label').text() );
		}
	});
	$('.textarea textarea').not('.alt').focus(function() {
		if( $(this).val()==$(this).parent().find('label').text() ) {
			$(this).val('');
		}
	});
	$('.textarea textarea').not('.alt').blur(function() {
		if( $(this).val()=='' ) {
			$(this).val( $(this).parent().find('label').text() );
		}
	});
	
	// ===================
	// = FORM VALIDATION =
	// ===================
	
	// we'll want to clear out the default values before validating...
	$("#rfpform").submit(function() {
		$('.textfield').each(function() {
			if( $(this).find('input').attr('value') == $(this).find('label').text() ) {
				$(this).find('input').attr('value', '');
			}
		});
		$('.textarea').each(function() {
			if( $(this).find('textarea').val() == $(this).find('label').text() ) {
				$(this).find('textarea').val('');
			}
		});
	});
	
	$("#rfpform").validate({
		invalidHandler: function(form) {
			$('.textfield').each(function() {
				if( $(this).find('input').attr('value') == '' ) {
					$(this).find('input').attr('value', $(this).find('label').text());
				}
			});
			$('.textarea').each(function() {
				if( $(this).find('textarea').val() == '' ) {
					$(this).find('textarea').val($(this).find('label').text());
				}
			});
		}
	});
	
}


// ===============
// = CYCLE SLIDE =
// ===============

function cycleslide() {
	if(hovering==false) {
		slideindex++;
		if( slideindex > ( photos.length - 1 ) ) {
			slideindex = 0;
		}
		targetslide = '#dotnav li:eq(' + slideindex + ') a';
		$(targetslide).trigger("click");
	}
	setTimeout('cycleslide()', slidetimeout);
}




$(document).ready(function() {
	
	if( $('#homepage').length != 0 ) {
	
		$('.slide_0').removeClass('slide_0').addClass('init');
	
		// =======================
		// = PRELOAD HUGE IMAGES =
		// =======================

		$('.preload').hide();
	
	
		// =================
		// = PREP ELEMENTS =
		// =================
	
		// add the dotnav
		$('#slideshow').append('<ul id="dotnav"></ul>');
		for (var i=0; i < photos.length; i++) {
			if( i == 0 ) {
				$('ul#dotnav').append('<li><a href="#"><img src="' + imgabspath + '/dot-active.png" alt="Active photo" /></a></li>');
			} else {
				$('ul#dotnav').append('<li><a href="#"><img src="' + imgabspath + '/dot-inactive.png" alt="Inactive photo" /></a></li>');
			}
		};
	
		// add the toggle
		$('#controls').append('<p id="toggle"><a href="#">Close</a></p>');
	
		// =============
		// = HANDLE IE =
		// =============
		if($.browser.msie && parseInt($.browser.version) <= 6) {
			$('img').each(function() {
				$(this).attr( 'src', str_replace( '.png', '.gif', $(this).attr('src') ) );
			});
		}
	
		hook_toggle();
		
		hook_dot_nav();
	
	}
	
	prep_forms();

});


$(window).load(function() {
	
	// ==================
	// = HANDLE PRELOAD =
	// ==================
	
	// we're preloaded so we can show our first slide
	$('#imageholder').fadeTo('fast', 0.01, function() {
		$('#imageholder').removeClass('init').addClass('slide_0');
		$('#imageholder').fadeTo('fast', 1);
	});
	
	
	// =================
	// = HANDLE PROMOS =
	// =================
	
	// we'll also start the promo cycle
	$('.hidden').removeClass('hidden').hide();
	if($('.promotion').length>1)
	{
		setInterval(function(){
			$('.promotion:eq(0)').fadeOut('slow')
				.next('.promotion').fadeIn('slow')
				.end().appendTo('#promo .inner');}, 
			8000);
	}
	

	// =====================
	// = SET AUTO ROTATION =
	// =====================
	if( $('#homepage').length != 0 ) {
		setTimeout('cycleslide()', slidetimeout);

		$('#dotnav').hover(function() {
			hovering = true;
		}, function() {
			hovering = false;
		});
	}
	
});
