$(document).ready(function(){
  
  Cufon.replace("#content li, #register label span.verbose, #forgot label span.verbose, #account label span.verbose, .asterisk",  { fontFamily: 'Proxima Nova Alt Rg italic' });
  Cufon.replace("#header .slogan, .testimonial span.author",  { fontFamily: 'Proxima Nova Alt Rg Semi Bold Italic' });
  Cufon.replace("#footer .left ul li, #header-wrapper .contact, #account .one-col-setup h2",  { fontFamily: 'Proxima Nova Alt Rg Bold' });
  Cufon.replace("#content h1, #main-nav li, #header-wrapper .contact .address, #contact h3, #side-bar-left ul li a, #account h2", { fontFamily: 'Proxima Nova Alt Lt', hover: true });
  Cufon.replace("#content p, #footer .copyright, #contact h2, ul.email-addresses li, #deposition-list-wrapper .row p a, #side-bar-right label span.verbose",  { fontFamily: 'Proxima Nova Alt Rg', hover: true });
  Cufon.replace("#footer .right",  { fontFamily: 'Proxima Nova Alt Rg Bold Italic' });
  
  setInterval("rotateFooterText()",4000);
    
	$('.rounded-corners').each(function(){
		$(this).corner({
			tl: { radius: parseInt($(this).attr("tl")) },
			tr: { radius: parseInt($(this).attr("tr")) },
			bl: { radius: parseInt($(this).attr("bl")) },
			br: { radius: parseInt($(this).attr("br")) }
		});
	});
	
	$("#side-bar-right #switch, #side-bar-right #arrow").live("click",function(){
	  
	  if(loggedIn)
	  {
	    window.location = webroot+"account";
	    return false;
	  }
	  
	  if($("#side-bar-right #slider").is(':animated'))
      return false;

	  if($("#side-bar-right #slider").css("top") == "-47px")
	  {
	    $("#side-bar-right #slider").animate({ top: '101px' },500);
	    $("#side-bar-right #arrow img").rotate({animateTo:90})
	  }
	  else
	  {
	    $("#side-bar-right #slider").animate({ top: '-47px' },500);
	    $("#side-bar-right #arrow img").rotate({animateTo:0})
	  }
	  
	});
  
  $('select.country').change(function(){
    
    var countryObj = $(this);

    var obj   = $("select[name='"+$(this).attr("state-name")+"']");
    var Name  = $(obj).attr("name");
    var Width = $(obj).attr("width");
    var ID    = $(obj).attr("id");
    
		submitAjax(webroot+"switch_states","country_id="+$(this).attr("value")+"&Name="+Name+"&Width="+Width+"&ID="+ID,function(r){
		  ajaxSwitchStatesPostCall(r);
		  var checkId = $(countryObj).attr("check");		  
		  if(checkId != undefined && $("#"+checkId).is(":checked"))
		    $("#"+$(countryObj).attr("state-name")).val($("#state_id").attr("value"));
		});
		
	});
  
  $("form").submit(function(event){
    //////////////////////////////////////////////
    // Already passed pre-checks, let it through
    //
    if($(this).attr("status") == "2")
	    return true;
	  
	  ////////////////////////////////////////////////////////////
	  // In the process of doing pre-checks, hold off until done
	  //
    if($(this).attr("status") == "0")
	    return false;
	  
	  $(this).attr("status","0");
	  
	  event.stopPropagation();
	  	  
	  submitForm($(this).attr("id"),checkFormCallBack,webroot+"check_form");
	  return false;
	});
  
  $("input.error, select.error, div.error").live("focus change click",function(){
    $(this).removeClass("error");
  });
  
});

var checkFormCallBack = function(r){
  if (r == '' || r == '0')
  {
    alert("ERROR: Could not talk to server.");
    $("form#"+response.FormName).attr("status","1");
  }
	else
	{
		var response = eval('('+r+')');

		if(response.Error)
		{
		  switch(true)
			{
				case response.ErrorMessage:
					alert(response.ErrorMessage);
					break;
					
				default:
				
					var missingFields = "";
					var additionalErrorMessages = "";
												
					if(response.MissingFields)
					{
						missingFields += "Missing Required Fields:\n";
						for(var i=0;i<response.MissingFields.length;i++)
						{									
							var field = response.MissingFields[i];
							var txt   = "";
																							
							$('label[for="'+field+'"] span.verbose cufontext').each(function(){							  
							  txt += $(this).html();
							});
																
							missingFields += "- "+txt+"\n";
														
							$("#"+field+", *[field='"+field+"']").each(function(){
							  $(this).addClass("error");
							});
						}
					}
										
					if(response.AdditionalErrorMessages)
					{								
						additionalErrorMessages += "Errors:\n";
						
						for(var i=0;i<response.AdditionalErrorMessages.Messages.length;i++)
							additionalErrorMessages += "- "+response.AdditionalErrorMessages.Messages[i]+"\n";
							
					  for(var j=0;j<response.AdditionalErrorMessages.Fields.length;j++)
						{
						  var field = response.AdditionalErrorMessages.Fields[j];

  					  $("#"+field+", *[field='"+field+"']").each(function(){
  					    $(this).addClass("error");
  						});
						}
					}
				
					var message = "";
				
					if(missingFields)
					{
						message += missingFields;
						
						if(additionalErrorMessages)
							message += "\n";
					}
				
					if(additionalErrorMessages)
						message += additionalErrorMessages;
					alert(message);

					break;
			}
			
			$("form#"+response.FormName).attr("status","1");
			return false;
		}
		else
		  $("form#"+response.FormName).attr("status","2").submit();
	}
}

var ajaxSwitchStatesPostCall = function(r){
	if (r == '' || r == '0')
		showStatus("ERROR: Could not talk to server.",false);
	else
	{
		var response = eval('('+r+')');

		if(response.Error)
			alert(response.ErrorMessage);
		else
			$("#"+response.ID+"-wrapper").html(response.HTML);
	}
}

var rotateFooterText = function(){
  
  var size = $("#footer .left ul li[class!='place-holder']").size();
  
  var oldIndex = 0;
  var newIndex = 0;
  
  $("#footer .left ul li[class!='place-holder']").each(function(index){
    if($(this).css("display") == "list-item")
    {
      oldIndex = index;
      
      if(index == (size-1))
        newIndex = 0;
      else
        newIndex = oldIndex+1;
    }
  });

  var oldObj = $("#footer .left ul li[class!='place-holder']")[oldIndex];
  var newObj = $("#footer .left ul li[class!='place-holder']")[newIndex];

  $(oldObj).fadeOut(750,function(){
    $(newObj).fadeIn(750);
  });
}

function showHide(show,group)
{	
	for(var i=0;i<group.length;i++)
	{	
		if(group[i] == show)
		{
			document.getElementById(group[i]).style.display = "block";
			document.getElementById(group[i]).disabled 		= false;
		}
		else
		{
			document.getElementById(group[i]).style.display = "none";
			document.getElementById(group[i]).disabled 		= true;
		}
	}
}

function clear_populate(default_val, object, event)
{
	switch(event)
	{
		case "clear":
			if(object.value == default_val)
				object.value = "";
			break;
		case "populate":
			if(object.value == "")
				object.value = default_val;
			break;
	}
}

function set_img_src(img,src)
{
	img.src = src;
}

var response_txt;

// AJAX call to do an inner HTML replace (using Prototype)
function ajaxReturnResponse(where,params,id,message,set_id)
{	
	if(message)
		document.getElementById(id).innerHTML = message;

	var response = new Ajax.Request(where,
    {
      	method: 'post',
      	parameters: params,
      	onSuccess: function(transport) {
	
			response_txt = transport.responseText;
	
			if(id)
        		document.getElementById(id).innerHTML = response_txt;

			if(set_id)
				set_input_text_val(set_id,response_txt);
		}
	});
}


/*
* Dynamic Web Coding - Scroll Bars
*/

function initScrollLayer(layer) {
  // arguments: id of layer containing scrolling layers (clipped layer), id of layer to scroll, 
  // if horizontal scrolling, id of element containing scrolling content (table?)
  wndo[0] = new dw_scrollObj('wn',layer);
  
  // bSizeDragBar set true by default (explained at www.dyn-web.com/dhtml/scroll/ )
  // wndo.bSizeDragBar = false;
  
  // arguments: dragBar id, track id, axis ("v" or "h"), x offset, y offset
  // (x/y offsets of dragBar in track)
  wndo[0].setUpScrollbar("dragBar", "track", "v", 1, 1);
  
  // pass id's of any wndo's that scroll inside tables
  // i.e., if you have 3 (with id's wn1, wn2, wn3): GeckoTableBugFix('wn1', 'wn2', 'wn3');
  // GeckoTableBugFix('wn'); 
}

// Necessary to avoid errors before page loaded 
function dw_startScroll(num, dir, sp) 
{
  	if(wndo[num] && wndo[num].startScroll) 
		wndo[num].startScroll(dir, sp);
}

function dw_stopScroll(num) 
{
  	if(wndo[num] && wndo[num].stopScroll) 
		wndo[num].stopScroll();
}

function dw_loadLayer(id) 
{
	for(var i=0;i<list.length;i++)
	{
		document.getElementById(list[i]+'_content').style.visibility = 'hidden';

		if(list[i] != id)
			document.getElementById(list[i]).style.color      = '#602D00';
		else
			document.getElementById(list[i]).style.color      = '#939379';
	}
	current_content = id;

	if(id == 'contact')
		document.getElementById('scrollbar').style.display = 'none';
	else
		document.getElementById('scrollbar').style.display = 'block';

	initScrollLayer(id+'_content');
}

// increase speed onmousedown of scroll links
function dw_doubleSpeed(num) 
{
  	if(wndo[num] && wndo[num].speed) 
		wndo[num].speed *= 2;
}

function dw_resetSpeed(num) 
{
  	if(wndo[num] && wndo[num].speed) 
		wndo[num].speed /= 2;
}

function switch_states(id,obj_id)
{
	var states 	= document.getElementById(obj_id).childNodes;
	var found	= false;

	for(var i=0; i<states.length; i++)
	{
		if(states[i].id)
		{
			if(states[i].id == (obj_id+'_'+id))
			{
				found = true;
				document.getElementById(states[i].id).style.display = "block";
				document.getElementById(states[i].id).disabled      =  false;
				document.getElementById(states[i].id).style.width 	= "250px";
			}
			else
			{
				document.getElementById(states[i].id).style.display = "none";
				document.getElementById(states[i].id).disabled      =  true;
			}
		}
	}
	
	if(document.getElementById(id))
		set_state(document.getElementById(id).childNodes[1].value);
}

function set_state(value)
{
	document.getElementById('state').value = value;
}

function show_table_row()
{
	var args = show_table_row.arguments;
	for(var i=0;i<args.length;i++)
	{
		if(navigator.appName.indexOf('Microsoft') != -1)
			document.getElementById(args[i]).style.display = 'inline';
		else
			document.getElementById(args[i]).style.display = 'table-row';
	}
}

function hide_obj()
{
	var args = hide_obj.arguments;
	for(var i=0;i<args.length;i++)
		document.getElementById(args[i]).style.display = 'none';
}

function set_input_text_val(id,val)
{
	document.getElementById(id).value = val;
}

function clear_text()
{
	var args = clear_text.arguments;
	for(var i=0;i<args.length;i++)
		document.getElementById(args[i]).value = '';
}

function uncheck_checkboxes()
{
	var args = uncheck_checkboxes.arguments;
	for(var i=0;i<args.length;i++)
		document.getElementById(args[i]).checked = false;
}

function check_checkboxes()
{
	var args = check_checkboxes.arguments;
	for(var i=0;i<args.length;i++)
		document.getElementById(args[i]).checked = true;
}


function set_select_menu(id,val)
{
	var obj = document.getElementById(id);
	
	for(var i=0; i<obj.options.length; i++)
		obj.options[i].selected=(obj.options[i].value==val);
}

function calculate_chars_left(id,max,curr_length)
{
	$("#chars-left").html(max - curr_length);
}

function check_max_chars(id,max)
{ 
	if($("#"+id).attr("value").length > max)
		$("#"+id).attr("value",$("#"+id).attr("value").substring(0,max));
}

function submitAjax(url,data,callBackFunction)
{
	$.ajax({
		data: data,
		url: url,
		type: 'POST',
		timeout: 10000,
		error: function() {
			alert("ERROR: Could not talk to server.");
		},
		success: function(r) {
			if(callBackFunction)
				return callBackFunction(r);
			else
			{
				var response = eval('('+r+')');

				if(response.Error)
					alert(response.ErrorMessage);
				else
					alert(response.Message);
			}
		}
	}); // ajax
}

function submitForm(form,callBackFunction,urlOverride)
{
	var formObj = $("form#"+form);	
	var url = $(formObj).attr("action");
	if(urlOverride)
		url = urlOverride;

	$.ajax({
		data: formObj.serialize(),
		url: url,
		type: 'POST',
		timeout: 10000,
		error: function() {
			alert("ERROR: Could not submit form.");
		},
		success: function(r) {
			if(callBackFunction)
			{
				return callBackFunction(r);
			}
			else
			{
				var response = eval('('+r+')');

				if(response.Error)
					alert(response.ErrorMessage);
				else
					alert(response.Message);
			}
		}
	}); // ajax
}
