// When DOM is ready (e.g. window.onload)....
$(document).ready(function(){
    
    // Initialize Cufon for non IE browsers
    /*@cc_on 	
        @if (@_jscript == false)
        */initCufon();/*
        @end 
    @*/
	
	// Initialize navigation rollovers
	initNavigationRollovers();
	
	// Initialize front page blocks
	initFrontBlocks();
	
	// Intitialze Practice rollovers
	initPracticeColumns();
	
	// Initialize form default values
	initFormDefaults();
	
	// Initialize Practice block rollover
	initPracticeBlock();
	
	// Initialize Table of Contents
	initTableOfContents();
        
    // Even out the product boxes
    initProductBoxes();
	
    // Google map
    initMap();
    
    // Team Photo Rollovers
    initTeamPhotos();
	
	// Subscription Form
	initSubscribeForm();
    
});

function initCufon() {
    Cufon.replace('h1', { fontFamily: 'trade-gothic-cn-18' });
    Cufon.replace('#column-container #left-column h2', { fontFamily: 'trade-gothic-bold' });
    Cufon.replace('#home_text h1', { fontFamily: 'trade-gothic-bd-cn-20' });    
    Cufon.replace('.home_list li p', { fontFamily: 'trade-gothic-cn-18' });
    Cufon.replace('#bottom_row_1 h2', { fontFamily: 'trade-gothic-bold' });
    Cufon.replace('#bottom_row_2 h2', { fontFamily: 'trade-gothic-bold' });
    Cufon.replace('.sidebar-box h2', { fontFamily: 'trade-gothic-bd-cn-20' });
    Cufon.replace('.sidebar-box p a', { fontFamily: 'trade-gothic-cn-18' });
    Cufon.replace('.small_headline_about_wrapper h2', { fontFamily: 'trade-gothic-bold' });
    Cufon.replace('.small_headline_wrapper h2', { fontFamily: 'trade-gothic-bold' });
}

// Rollover related...
var mouseOvers = new Array();
var mouseOuts = new Array();
function mouseGoesOver() { this.src = mouseOvers[this.number].src; }
function mouseGoesOut() { this.src = mouseOuts[this.number].src; }

// Initialize our navigation rollovers...
function initNavigationRollovers()
{
	var imgs = document.getElementById('navigation').getElementsByTagName('img');
	// Add mouseover events to our navigation images
	for (var i=0;i<imgs.length;i++) {
		if (imgs[i].parentNode.className == "active") { 
			// If the image's parent has a class of "active" then don't do the rollover for it, instead show the active state only
			var suffix = imgs[i].src.substring(imgs[i].src.lastIndexOf('.'));
			imgs[i].src = imgs[i].src.substring(0,imgs[i].src.lastIndexOf('.')) + "_on" + suffix;
		} else {
			// If the image has a class of blank, skip it
			if (imgs[i].className == "blank") continue;
			imgs[i].onmouseover = mouseGoesOver;
			imgs[i].onmouseout = mouseGoesOut;
			var suffix = imgs[i].src.substring(imgs[i].src.lastIndexOf('.'));
			mouseOuts[i] = new Image();
			mouseOuts[i].src = imgs[i].src;
			mouseOvers[i] = new Image();
			mouseOvers[i].src = imgs[i].src.substring(0,imgs[i].src.lastIndexOf('.')) + "_on" + suffix;
			imgs[i].number = i;
		}
	}
}


// Initialize hoverable front page blocks...
temp_bg_image_holder = new Array();
function initFrontBlocks()
{
	// if the bottom_row_1 exists, preload some background images for our hover states
	if ( $("div#bottom_row_1").get(0) != undefined)
	{
		temp_bg_image_holder[0] = new Image();
		temp_bg_image_holder[0].src = "/includes/images/bg_square_l_top_on.gif";
		temp_bg_image_holder[1] = new Image();
		temp_bg_image_holder[1].src = "/includes/images/bg_square_l_bottom_on.gif";
		temp_bg_image_holder[2] = new Image();
		temp_bg_image_holder[2].src = "/includes/images/bg_square_x_top_on.gif";
		temp_bg_image_holder[3] = new Image();
		temp_bg_image_holder[3].src = "/includes/images/bg_square_x_bottom_on.gif";
		temp_bg_image_holder[4] = new Image();
		temp_bg_image_holder[4].src = "/includes/images/bg_square_x_top_on.gif";
		temp_bg_image_holder[5] = new Image();
		temp_bg_image_holder[5].src = "/includes/images/bg_square_x_bottom_on.gif";
		temp_bg_image_holder[6] = new Image();
		temp_bg_image_holder[6].src = "/includes/images/bg_square_r_top_on.gif";
		temp_bg_image_holder[7] = new Image();
		temp_bg_image_holder[7].src = "/includes/images/bg_square_r_bottom_on.gif";
	}
	
	// Add css and onclick event to our blocks
	$("div#bottom_row_1 > div").each(function(i) {
	  $(this).bind("mouseover", function() {
		  $(this).addClass("on");
		}).bind("mouseout", function() {
			$(this).removeClass("on");
		}).bind("click", function() {
			// grabs the first link found (so make sure the first link is the destiation!)
			location.href = $("a", this).get(0).getAttribute('href');
		});
	});
	
	$("div#bottom_row_2 div div div").each(function(i) {
	  $(this).bind("mouseover", function() {
		  $(this).addClass("on");
		}).bind("mouseout", function() {
			$(this).removeClass("on");
		}).bind("click", function() {
			// grabs the first link found (so make sure the first link is the destiation!)
			location.href = $("a", this).get(0).getAttribute('href');
		});
	});
	
}

temp_practices_image_holder = new Array();
function initPracticeColumns(){
	if ( $("div#practices_content").get(0) != undefined)
	{
		temp_practices_image_holder[0] = new Image();
		temp_practices_image_holder[0].src = "/includes/images/bg-smallest-box-header_on.gif";
		temp_practices_image_holder[0] = new Image();
		temp_practices_image_holder[0].src = "/includes/images/bg-smallest-box-middle_on.gif";
	}
		
	// Add css and onclick event to our blocks
	var a = 0;
	$(".practices_tophalf").each(function(i) {		
	  $(this).bind("mouseover", function() {$(this).addClass("on");}).bind("mouseout", function() {
			$(this).removeClass("on");
		}).bind("click", function() {
			// grabs the first link found (so make sure the first link is the destination!)
			location.href = $("a", this).get(0).getAttribute('href');
		});
	});
    
    // determine max heights
    var maxTotalHeight = 0;
    var maxBottomHeight = 0;
    var thisHeight = 0;
    $(".smallest-box").each(function(i){
        thisHeight = $(".smallest-box:nth(" + i + ")").height();
        if (thisHeight > maxTotalHeight) {
            maxTotalHeight = thisHeight;
        }
        thisHeight = $(".smallest-box:nth(" + i + ") .bottom").height();
        if (thisHeight > maxBottomHeight) {
            maxBottomHeight= thisHeight;
        }
    });
    
    // now assign the heights
    $(".smallest-box").each(function(i) {
        $(".smallest-box:nth(" + i + ")").height(maxTotalHeight)
        $(".smallest-box:nth(" + i + ") .bottom").height(maxBottomHeight);
    })
    
    // assign arrowed class to last anchor tag in .bottom div
    // $(".smallest-box .bottom > a:last-child").addClass("arrowed");
    
}

// Initialize hoverable practice block
temp_practice_bg_image_holder = new Array();
function initPracticeBlock()
{
	// if the practice exists, preload some background images for our hover states
	if ( $(".sidebar-box").get(0) != undefined)
	{
		temp_practice_bg_image_holder[0] = new Image();
		temp_practice_bg_image_holder[0].src = "/includes/images/bg_practice_on.gif";
	}
	// Add css and onclick event to our practice block
	$(".sidebar-box").each(function(i) {
	  $(this).bind("mouseover", function() {
		  $(this).addClass("sidebar-box_on");
		}).bind("mouseout", function() {
			$(this).removeClass("sidebar-box_on");
		}).bind("click", function() {
			// grabs the first link found (so make sure the first link is the destiation!)
			location.href = $("a", this).get(0).getAttribute('href');
		});
	});
}


// Initialize default form values and functionality...
function initFormDefaults()
{
	$('.submit input').bind("click",function () {
		clearRequiredFields();								
	});
	// Find each input or textarea field that needs default text (.add_default_text)
	$('.add_default_text').each(function(i) {
		var start_value = this.getAttribute('value');
		var list_of_defaults = new Array();
		var new_default_text = "";
		// compile list of default texts that should be added
		if (this.className.indexOf('add_required') > -1) list_of_defaults.push('Required');
		if (this.className.indexOf('add_hidden') > -1) list_of_defaults.push('Hidden');
		if (this.className.indexOf('add_optional') > -1) list_of_defaults.push('Optional');
		// add default text. will look something like: (Required, Hidden) etc..
		// do not over write any pre-existing text
		// check for password fields
		if (list_of_defaults.length > 0)
		{
			new_default_text = "(";
			for(i=0;i<list_of_defaults.length;i++) {
				new_default_text += list_of_defaults[i];
				if (list_of_defaults.length-1 != i) new_default_text += ", ";
			}
			new_default_text += ")";
			if (this.value == '') {
				this.value = new_default_text;
				if ($(this).attr("type") == "password") {
					$(this).attr("type","input");	
				}					
			}
			if (this.value != new_default_text) {
				$(this).removeClass("add_default_text");
			}		
		}
		// Function that will check to see if anything changes in the value, 
		// if it does do nothing, if not put the default text back
		$(this).bind("focus", function () {
			if (this.value == new_default_text) {
				this.value = ''; 
				$(this).removeClass("add_default_text");
				if ($(this).attr("id") == "user_pass") {
					$(this).attr("type","password");
				}
			}
		});
		$(this).bind("blur", function () { 
			if (this.value == '') { 
				this.value = new_default_text; 
				$(this).addClass("add_default_text"); 
				if ($(this).attr("type") == "password") {
					$(this).attr("type","input");	
				}
			} 
		});
	});
}

// We want to clear required fields before submitting so that 
// we can do server side validation.
function clearRequiredFields() {
	$('input').each(function(i) {
		if (this.value == '(Required)') {
			this.value = '';	
		}
	})
}

// Initialize table of contents
function initTableOfContents()
{
	// if the table of contents exists, set it to hide
	$(".table_of_contents").each(function(i) {
		$(this).addClass("hide_table_of_contents");
		$(this).find(".plus_or_minus").html("+"); // change the symbol to +
	});
	// Add css and onclick event to our table of contents link
	$(".table_of_contents_link").each(function(i) {
	  $(this).bind("click", function() {
			if (this.parentNode.className.indexOf('hide_table_of_contents') > -1) // if table of contents is hidden, show it..
			{
				$(this.parentNode).removeClass("hide_table_of_contents");
				$(this).find(".plus_or_minus").html("&ndash;"); // change the symbol to -
			}
			else // or hide it
			{
				$(this.parentNode).addClass("hide_table_of_contents");
				$(this).find(".plus_or_minus").html("+"); // change the symbol to +
			}
			return false; // don't follow the href
		});
	});
}

// Normalize the product box heights and handle last child actions
function initProductBoxes()
{
        if ( $("#product-box-left").get(0) != undefined) {
                $(document).ready(function(){
                        var leftHeight = $("#product-box-left .content").height();
                        var rightHeight = $("#product-box-right .content").height();
                        
                        if ( leftHeight >= rightHeight ) {
                                $("#product-box-right .content").height(leftHeight + "px");
                        }
                });
        }
        
        $("#product-box-left .content ul li:last-child").addClass("last");
        
        $("#product-box-left .content ul li:last-child").hover(function(){
           $("#product-box-left .footer").addClass("on");
         },function(){
           $("#product-box-left .footer").removeClass("on");
         });
        
}

// Google Map API
function initMap()
{
        var map = document.getElementById("map");
        if (map != null)
        {
                //<![CDATA[
                function loadMap() {
                        if (GBrowserIsCompatible()) {
							
								var icon = new GIcon();
								icon.image = "/includes/images/gmap_icon.png";
								icon.shadow = "/includes/images/gmap_icon_shadow.png";
								icon.iconSize = new GSize(35, 28);
								icon.shadowSize = new GSize(44, 28);
								icon.iconAnchor = new GPoint(6, 20);
								icon.infoWindowAnchor = new GPoint(5, 1);
							
                                var map = new GMap2(document.getElementById("map"));
                                var point = new GLatLng(30.268908, -97.740437);
                                var marker = new GMarker(point, icon);
                                map.addControl(new GSmallMapControl());
                                map.setCenter(point, 13);
                                map.addOverlay(marker);
                        }
                }
                //]]>
                var map = loadMap();
        }
}

// Initialize the Team Photos
function initTeamPhotos()
{
	var navRoot = document.getElementById("photos");
	if(navRoot != null)    
	{
		var lis = navRoot.getElementsByTagName("div");
		if(lis != null)
		{
			for (var i=0; i<lis.length; i++)
			{
				if (lis[i].parentNode.id == "photos")
				{
					lis[i].onmouseover = function()
					{
						this.className += " hover";
					}
					lis[i].onmouseout = function()
					{
						this.className = this.className.replace("hover");
					}
				}
			}
		}
	}
}


// Initialize Subscription Form
function initSubscribeForm()
{
	if ( $("#subscribeform").get(0) != undefined) {
		$('#subscribeform').ajaxForm({ 
			target: '#subscribe-result', 
			beforeSubmit: function() {
				$('#spinner').css('visibility','visible');
				$('#submit').attr('disabled','disabled');
	
				var checkbox = $('#subscribeform input[@name=subscribe]').fieldValue();
				if (checkbox != 'on') {
					$('#spinner').css('visibility','hidden');
					$('#submit').removeAttr('disabled');
					// $('#subscribeText').css('color','red');
					$('#try-again').empty();
					$('#try-again').append("<span style='color: red';>Please check the box if you would like to subscribe.</span>");
					return false;
				}
	
				$('#subscribe-before').fadeOut('slow');
			},
			success: function() { 
				$('#spinner').css('visibility','hidden')	
				$('#subscribe-result').fadeIn('slow');	
			}
		});
	}
}

// Needed by wordpress admin for our hacked login
function addLoadEvent(func) {if ( typeof wpOnload!='function'){wpOnload=func;}else{ var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}}