


// load values from attribute 'defalutval' into input fields'
function loadvals (evt)
{
	line = evt.parentNode.parentNode;
	/*if ( line.nextSibling.className == 'values' )
	{
		valline = line.nextSibling;
	}
	else
	{*/
		valline = line.parentNode.insertBefore ( document.createElement ( 'TR' ), line.nextSibling );
	//}
	valline.className = 'values';
	c = valline.appendChild ( document.createElement ( 'td' ) );
	c.innerHTML = '&nbsp;';
	inputs = line.getElementsByTagName ( 'INPUT' );
	for ( x = 0; x < inputs.length; x++ )
	{
		if ( $(inputs[x]).attr( 'default' ) )
		{
			c = valline.appendChild ( document.createElement ( 'td' ) );
			//inputs[x].value = inputs[x].attributes['default'].value;
			c.innerHTML = inputs[x].attributes['default'].value;
		}
	}
	$(evt).fadeOut ( 'fast' );
}


//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var activePopup;
var lfocus;

function loadfarm ()
{
	//loads popup only if it is disabled
	if ( popupStatus == 0 )
	{
		activePopup =  "#popupLoad" ;
		$( "#backgroundPopup" ).css ( { "opacity": "0.7" } );
		$( "#backgroundPopup" ).fadeIn ( "slow" );
		$( activePopup ).fadeIn ( "slow" );
		popupStatus = 1;
		i = $( activePopup + " input:visible"); //.focus();
		$(i[0]).focus();
	}
	return false;
}

function savenotice ()
{
	//loads popup only if it is disabled
	if ( popupStatus == 0 )
	{
		activePopup =  "#savenotice" ;
		$( "#backgroundPopup" ).css ( { "opacity": "0.7" } );
		$( "#backgroundPopup" ).fadeIn ( "fast" );
		$( activePopup ).fadeIn ( "fast" );
		
		//$( "#savebox" ).dialog ({bgiframe: true,height:300,modal:true,buttons:{'Save':function(){$(this).dialog('close');}}});
		popupStatus = 1;
	}
	return false;
}

function savefarm ()
{
	//loads popup only if it is disabled
	if ( popupStatus == 0 )
	{
		activePopup =  "#popupSave" ;
		$( "#backgroundPopup" ).css ( { "opacity": "0.7" } );
		$( "#backgroundPopup" ).fadeIn ( "slow" );
		$( activePopup ).fadeIn ( "slow" );
		i = $( activePopup + " input:visible"); //.focus();
		$(i[1]).focus();
		//$( "#savebox" ).dialog ({bgiframe: true,height:300,modal:true,buttons:{'Save':function(){$(this).dialog('close');}}});
		popupStatus = 1;
	}
	return false;
}


//disabling popup with jQuery magic!
function disablePopup()
{
	//disables popup only if it is enabled
	if ( popupStatus == 1 )
	{
		$( "#backgroundPopup" ).fadeOut("slow");
		$( activePopup ).fadeOut("slow");
		popupStatus = 0;
		try {
		if ( lfocus[0] != null )
			$(lfocus[0]).focus();
		}
		catch ( e )
		{}
	}
}


//centering popup
function centerPopup()
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $( activePopup ).height();
	var popupWidth = $( activePopup ).width();
	
	//centering
	$(activePopup).css( 
		{
			"position": "absolute",
			"top": windowHeight/2-popupHeight/2,
			"left": windowWidth/2-popupWidth/2
		});
	//$("#popupSaveTitle").css({"width":popupWidth});
	//only need force for IE6
	$("#backgroundPopup").css ( {"height": windowHeight } );

}

function showloadfarm(e)
{
	centerPopup();
	loadfarm();
	return false;
}

var cookies = new Array ; 
function showsavefarm(e)
{
	centerPopup();
	c = document.cookie.split(/; /);
	cookie = false ;
	for (i in c)
	{
		t = c[i].split(/=/,2);
		//cookies[$t[0]] = t[1];
		if ( t[0] == 'skipnotice' && t[1] == 'true' )
			cookie = true ;
	}
	if ( cookie == true )
		savefarm();
	else
		savenotice ();
	return false;
}

contenthidden = false ;
contentloaded = false ;
newhtmlcontent = ''

function pagesubmit ()
{
	if ( debug )
		debuga = 'debug=true&';
	else
		debuga = '';
	pagen = $("#pageform [name=control]" ).val();
	if ( shortf != 0 )
	{
		pagen++;
		//debuga = debuga + 'short=true&';
		$("#pageform [name=control]" ).val(pagen);
		shortf = 0;
	}
	if ( back != 0 )
	{
		if ( pagen > 0 && pagen < 12 )
			window.location.hash = pagen - 2;
		url = debuga + 'frag=true&back=true&' + $("#pageform" ).serialize() ;
		back = 0;
	}
	else
	{
		if ( pagen > 0 && pagen < 12 )
			window.location.hash = pagen;
		url =  debuga + 'frag=true&' + $("#pageform" ).serialize() ;
	}
	lhash = window.location.hash;
	contenthidden = false;
	contentloaded = false;
	$("#center").fadeOut ( "slow", function () { contenthidden = true; if ( contentloaded ) {  newcontent (); } } );	
	$.post ( "index.php", url, 
			function (data, status)
			{
				//alert ( data );
				contentloaded = true;
				newhtmlcontent = data;
				if ( contenthidden )
				{
					newcontent ();
					contenthidden = false;
				}
			},
			"html"
			);
	return false;
}

function newcontent ()
{

	oh = $("#center").width();
	$("#center").html ( newhtmlcontent );
	$("#center").fadeIn("slow",ready);
	if ( oh * 10 < $("#center").width() )
	{
		$("#center").css("max-width",oh );
		$("#center").css("margin-right",'4em');
	}
	$(".inputerror").bind ( "focus change", function () { $(this).removeClass( 'inputerror' ); $(this).css('background',''); } );	
}

function showcenter ()
{
	$("#center").css ( "overflow", "visible" ); 
	$("#center").css('height', '');
}

function savesubmit ()
{
	if ( $("#savefile:checked").val() ) 
	{
		$( "#backgroundPopup" ).fadeOut("slow");
		$( activePopup ).fadeOut("slow");
		popupStatus = 0;
		return true;
	}
	else
	{
		url = 'ajax=true&';
		$.post ( "index.php", url + $("#saveform" ).serialize() , 
			function (data, status)
			{
				if ( data.match ( /^Saved/i ) )
				{
					$( activePopup ).fadeOut("fast",function (){
					$("<div id='saveresult' >Saved</div>").appendTo("body") ;
					activePopup = "#saveresult";
					$( "#saveresult" ).css( 
					{
						"border": "1px solid black",
						"color": "white",
						"opacity": 1,
						"z-index": 3,
						"font-color": "white"
					});
					centerPopup();
					centerPopup();
					$( "#saveresult" ).css( 
					{
						"border": "0px solid black"
					});
					$('#saveresult').effect ( "puff",{percent: 2000},750,
					function () 
						{ 
						$( "#backgroundPopup" ).fadeOut("fast",function () {  $("#saveresult").remove (); popupStatus = 0;}); 
						} ); 
					});  
				}
				else if ( data.match ( /pass/i ) ) 
				{
					$(activePopup).find('.password').css('border','1px solid red');
					$(activePopup).find('.password').change(function (){$(this).css('border','');});
					alert ( "you must enter a password" );		
				}
				else
				{
					//$(activePopup).replaceWith ( data );
					alert ( data );		
					go ( parseInt ( window.location.hash.replace ( /#/,'') ) );
				}
				return false;
			},
			"text"
			);
		return false;
	}
}

function loadsubmit ()
{
}

function pagechange ()
{
	url = "goto=true&frag=true&control=" + $("#pageselect").val();
	contenthidden = false;
	contentloaded = false;
	window.location.hash = $("#pageselect").val();
	lhash = window.location.hash;
	$("#center").fadeOut ( "slow", function () { contenthidden = true; if ( contentloaded ) {  newcontent (); } } );	
	$.post ( "index.php", url, 
			function (data, status)
			{
				//alert ( data );
				contentloaded = true;
				newhtmlcontent = data;
				if ( contenthidden )
				{
					newcontent ();
					contenthidden = false;
				}
			},
			"html"
			);
	return false;

}

back = 0;
shortf = 0;
upload = false;
debug = false;
var lhash = window.location.hash;
function monitor ()
{
	if ( window.location.hash != lhash )
	{
		pagen = parseInt ( window.location.hash.replace ( /#/,'') );
		if ( pagen > 0 && pagen < 12 )
		{ 
			lhash = window.location.hash;
			go(pagen);
		}
		else
			lhash = window.location.hash;
	}
}

function go ( pagen )
{
			url = "goto=true&frag=true&control=" + pagen; 
			contenthidden = false;
		  contentloaded = false;
		  $("#center").fadeOut ( 1 , function () { contenthidden = true; if ( contentloaded ) {  newcontent (); } } );
		  $.post ( "index.php", url,
		      function (data, status)
		      {
		        //alert ( data );
		        contentloaded = true;
		        newhtmlcontent = data;
		        if ( contenthidden )
		        { 
		          newcontent ();
		          contenthidden = false;
		        }
		      },
		      "html"
	      );
}



function ready ( ) 
{ 
	i = $("#center input:visible:enabled"); //.focus();
	try {
		if ( $(i[0]).val() != 'Start' && $(i[0]).val() != 'I Agree' && i[0].form.name != 'surveyform' )
			$(i[0]).focus();
	}
	catch ( e ) {}
	$("#center FORM:eq(0) INPUT:visible").bind ( 'blur' , function () { lfocus = $(this); } );
	$("#back").click ( function () { back = 1 ; } ) ;
	$("#short").click ( function () { shortf = 1 ; } ) ;
	$("#hideadasurvey").click ( function () { $(".survey").fadeOut("slow"); document.cookie = 'hideadasurvey=true; expires=Fri, 31 Dec 2012 23:59:43 UTC; path=/'; return false;  } );
	
	$("#State").bind ( "change", 
		function () 
		{
			eval ( 'var counties = ' + $('#statemap').text() );
			$('#County').replaceWith ( '<select name="County" id="County" size="1"></select>' );
			cinp = $('#County');
			state = $("#State").val();
			for ( var c in counties [ state ] )
			{
				cinp.append('<option name="' + counties[state][c] + '" value="' + counties[state][c] + '" >' + counties[state][c] + '</option>');
			}
			setTimeout ( function () { $('#County').focus(); }, 50 );
		} );
	$("#pageform").action = '' ;
	$("#pageform").method = '' ;
	$("#pageform").submit ( function () { return pagesubmit (); } ) ;
	
	$(".inputerror").bind ( "focus change", function () { $(this).removeClass( 'inputerror' ); $(this).css('background',''); } );	
	$("#saveform").action = '' ;
	$("#saveform").method = '' ;
	$("#saveform").submit ( function () { 
			z= $('[name=email]')[0]; 
			if ( z.value.match ( /[a-zA-Z0-9.,_+-]+@[a-zA-Z0-9.-]+\.\w{2,4}/ ) )
			{
				$(z).css('border', '1px solid black'); 
				z= $('[name=password]')[0]; 
				if ( z.value.length > 3 )
				{
					$(z).css('border', '1px solid black'); 
					return savesubmit ();
				}
				else
				{ 
					$(z).focus(); 
					$(z).effect ( "bounce",{times: 2},300 );
					$(z).css('border', '1px solid red'); 
					return false;
				}
			}
			else
			{ 
				$(z).focus(); 
				$(z).effect ( "bounce",{times: 2},300 );
				$(z).css('border', '1px solid red'); 
				return false;
			} 
		} ) ;
	$("#loadform").submit ( function () { loadsubmit (); } );
	
	$("#pageselect").change ( function() { pagechange(); } );
	
	//Click out event!
	$("#backgroundPopup").css ( {'width': $(window).width() } );


	if ( $('.report') )
	{
		$('.report TR TD:first-child').css ( {'border-right': '2px solid black', 'align': 'left', 'text-align': 'left', 'padding-left': '2em', 'font-weight': 'bold' } );
		$('.report THEAD TD:first-child').css ( {'border-right': '2px solid black', 'text-align': 'left' } );
		$('.report .programtable TR TD:first-child').css ( {'border-right': '2px solid black', 'text-align': 'left' } );
		$('.report .programtable THEAD TD:first-child').css ( {'border-right': '2px solid black', 'text-align': 'left' } );
		$('.report .programtable TR:nth-child(odd) TD + TD:last-child').css ( { 'background-color': '#EFEFEF', 'font-weight': '500' } );
		$('.report .programtable TR:nth-child(even) TD + TD:last-child').css ( { 'background-color': '#E0E0E0', 'font-weight': '500' } );
		$('.report .programtable THEAD TD:last-child').css ( { 'font-weight': '600' } );
		$('.report .programtable THEAD:nth-child(2)').css ( { 'margin-top': '1em' } );
		$('.report TBODY TR:nth-child(even)').css ( { 'background-color': '#EDEDED' } );
		$('.report .plantedinfo TR:nth-child(1)').css ( { 'width': '14em' } );
		$('.report .plantedinfo TR:nth-child(1)').css ( { 'min-width': '14em' } );
		$('.report .cropsummary TR:nth-child(even)').css ( { 'border-bottom': '4px solid #777' } );
		$('.report .cropsummary TR:nth-child(odd) .acres').css ( { 'background-color': '#EFEFEF' } );
		$('.report .cropsummary TR:nth-child(even) .acres').css ( { 'background-color': '#E0E0E0' } );
		
		$('.report .labelrow ' ).css ( { 'background-color': '#FFF', 'border-top': '1px solid #888' } );
		$('.report .labelrow TD:first-child' ).css ( { 'padding-left': '0em' } );
		$('.report .annualsummary .labelrow').css ( { 'border-top': '2px solid black' } );	
		$('#acrehead' ).css ( { 'padding-top': '1em' } );
		//$('.report .cropsummary TABLE:first TR:nth-child(odd) TD:gt(2):lt(6)').css ( { 'background-color': '#E0E0E0' } );
		$('.explanation').live ( 'click', function ( ) {  
				mtitle = this.parentNode.firstChild.textContent;
				if ( ! mtitle ) 
				  mtitle = this.parentNode.innerText;
				$('#dialog').html( '<iframe src="' + this.href + '" width="100%" style="height:100%" >Problem displaying document, please <a href="' + this.href + '" target="_blank" >try again.</a></iframe>' ); 
				$('#dialog').dialog( { width: ( $(window).width() * .9), height:  ( $(window).height() * .85), modal: true, title: mtitle, autoOpen: true, close: function ( e,u) { $(this).dialog('destroy');} } ); 
				$('#dialog').dialog('open');
				return false;} );
	}
	
	jQuery.each(jQuery.browser, function(i) {
		if($.browser.msie && jQuery.browser.version.substr(0,3)=="6.0" ){
			//$("BODY").css({ "font-size": "10px" });
			//$("TABLE *").css({ "font-size": "10px" });
			$('<style media="print"> BODY { font-size: 10px; } TABLE * { font-size: 10px; } .report { width: 650px; } </style>').appendTo('head'); 
		}
	});

	//CLOSING POPUP
	//Click the x event!
	$("#popupSaveClose").css ( {'width': '1em' } );
	$("#popupLoadClose").css ( {'width': '1em' } );
	$("#savenoticeClose").click ( function() { disablePopup(); } );
	$("#popupSaveClose").click ( function() { disablePopup(); } );
	$("#popupLoadClose").click ( function() { disablePopup(); } );
	
	$("#backgroundPopup").click ( function() { disablePopup(); } );
	x=$(".loadvals");
	for ( i=0; i < x.length; i++ )
	{
		l = x[i];
		if ( l.attributes['vis'].value == 'no' ) 
		{
			$(l).hide(); //fadeOut ( 0 );
		}
		$(l).click (  function () { loadvals ( $(this)[0] ); return false;  } );
		line = l.parentNode.parentNode;
		inputs = line.getElementsByTagName ( 'INPUT' );
		for ( y = 0; y < inputs.length; y++ )
		{
			$(inputs[y]).keypress ( function () 
					{ link = $(this.parentNode.parentNode.getElementsByTagName ( 'A' )[0]); 
					if ( this.hasAttribute('default')){
					if ( this.value != this.attributes['default'].value  && this.attributes['default'].value != ' ' ) { 
					link.fadeIn('fast'); 
					} } } ) ;
		}
	}
	$("#loadfile").click ( function() { 
			if ( upload == false )
			{
				upload = true;
				$.get ( "index.php?control=93&frag=true&ajax=true", 
						function (data, status)
						{
							$("#center").append ( data );			
							//alert ( data );
							$("#popupUploadClose").click ( function() { disablePopup(); } );
							$( "#popupLoad" ).fadeOut ( "fast", function () { activePopup =  "#popupUpload" ; centerPopup();centerPopup();$( "#popupUpload" ).fadeIn ( "fast" ); } ); 
						},
						"html"
					);
			}
			else
				$( "#popupLoad" ).fadeOut ( "fast", function () { activePopup =  "#popupUpload" ; $( "#popupUpload" ).fadeIn ( "fast" ); } ); 
			return false;
			} );
	$("#ok").click ( function() { $( "#savenotice" ).fadeOut ( "fast", function () { activePopup =  "#popupSave" ; $( "#popupSave" ).fadeIn ( "fast" ); } ); return false;} );
	$("#okah").click ( function() { document.cookie = 'skipnotice=true; expires=Fri, 31 Dec 2012 23:59:43 UTC; path=/';
			$( activePopup ).fadeOut ( "fast", function () { activePopup =  "#popupSave" ; $( activePopup ).fadeIn ( "fast" ); } ); return false;} );
	activePopup =  "#savenotice" ;
	centerPopup();
	centerPopup();
	activePopup =  "#popupSave" ;
	centerPopup();
	centerPopup();
	activePopup =  "#popupLoad" ;
	centerPopup();
	centerPopup();
	window.scrollTo( 0,0 );
} 

$(document).ready ( function (){ 
		pagen = parseInt  ( window.location.hash.replace ( /#/ , '') );
		if ( parseInt ( $('#newsession').html() ) != pagen && pagen > 0 && pagen < 12 )
		{
			go(pagen);
		} 
		setInterval ( monitor, 75 ); 
		ready(); 
} );

//Press Escape event!
$(document).keypress
	( function(e)
		{
			if(e.keyCode==27 && popupStatus==1)
			{
				disablePopup();
			}
		}
);
