/* global inputline stuff */

var alertleftoffset=455;
var alertfadeinspeed='fast';
var alertfadeoutspeed='fast';
	
var focusseditem=false;
	
var focussedinputlineid=0;
var focussedtradingperiodid=0;


$(document).ready( function()
{
	var awesomeform=$('#awesomeform');
	
	$('.nojavascriptsubmit').hide();
	$('.javascriptsubmit').show();
	
	/************ inputline alerts *************/
	
	$('.inputline input', awesomeform).bind('focus', function() {
		showInputlineAlert($(this).parent().parent().parent());
	});

	$('.inputline textarea', awesomeform).bind('focus', function() {
		showInputlineAlert($(this).parent().parent().parent());
	});
	
	$('.inputline select', awesomeform).bind('focus', function() {
		showInputlineAlert($(this).parent().parent().parent());
	});
	
	$('.inputline .ui-datepicker-trigger', awesomeform).livequery('click', function() {
		showInputlineAlert($(this).parent().parent().parent());
	});
	
	$('.inputline input[type="checkbox"]', awesomeform).bind('click', function() {
		showInputlineAlert($(this).parent().parent().parent());
	});
	
	$('.inputline', awesomeform).bind('click', function() {
		showInputlineAlert($(this));
	});
	
	$("input").livequery('focus', function() {
		focusseditem = $(this);
		if (-1 == focusseditem.closest("div").attr("class").search(/inputline/) &&
			!focusseditem.parent().is("td"))
		{
			// hide all alerts and show the helper
			showHelper();
		}
	});
	
	
	/************ bid submission table alerts *************/
	/************ this is on its own page *****************/
	$('#bidsubmission input', awesomeform).bind('focus', function() {
		showSubmissionInputlineAlert($(this).parent());
	});
	$('#bidsubmission tr td:gt(0)', awesomeform).bind('click', function() {
		showSubmissionInputlineAlert($(this));
	});
	$('#bidsubmission tr td:eq(0)', awesomeform).bind('click', showHelper); // not nice but ok


	$("#bidsubmission input").livequery('focus', function() {
		focusseditem = $(this);
		if (-1 == focusseditem.closest("td").attr("class").search(/inputline/))
		{
			// hide all alerts and show the helper
			showHelper();
		}
	});	
	
	$('.validationalert').removeClass('validationalert').addClass('validationalertjscript');

	function showInputlineAlert(inputline)
	{
		thisinputlineid=getID(inputline.attr('id'));
		
		//don't change anything if we've refocussed on an input
		// in the currently focessed input line (e.g. day/month/year selects)
		if (thisinputlineid==focussedinputlineid)
			return;
		
		if ($("#formhelper").is(":visible"))
		{
			$("#formhelper").fadeOut(alertfadeoutspeed);
		}
	
		clearAlerts();
		focussedtradingperiodid=0;
	
		var position=inputline.position();
		focussedinputlineid=thisinputlineid;
		var validationinputline=inputline.attr('class').search(/validationalertinputline/);
		
		if (-1!=validationinputline)
		{
			$('#validationalert_'+focussedinputlineid, awesomeform).css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}
		else if (0!=$('#focusalert_'+focussedinputlineid, awesomeform).length)
		{
			inputline.addClass('focussedinputline');
			$('#focusalert_'+focussedinputlineid, awesomeform).css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}
	}

	// this is only for bid submission input lines
	function showSubmissionInputlineAlert(inputline)
	{
		thisinputlineid=getID(inputline.attr('id'));
		
		if (thisinputlineid==focussedinputlineid)
			return;
		
		if ($("#formhelper").is(":visible"))
		{
			$("#formhelper").fadeOut(alertfadeoutspeed);
		}
	
		clearAlerts();
		focussedtradingperiodid=0;
	
		var leftposition = inputline.closest("table").position();
		var topposition = inputline.position();
		focussedinputlineid=thisinputlineid;
		var validationinputline=inputline.attr('class').search(/validationalertsubmissioninputline/);
		
		if (-1!=validationinputline)
		{
			$('#validationalert_'+focussedinputlineid, awesomeform).css({'top':topposition.top,'left':leftposition.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}
		else if (0!=$('#focusalert_'+focussedinputlineid, awesomeform).length)
		{
			inputline.addClass('focussedinputline');
			$('#focusalert_'+focussedinputlineid, awesomeform).css({'top':topposition.top,'left':leftposition.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}
	}

	/************ trading periods alerts *************/
	
	$('.tradingperiod select', awesomeform).livequery('focus', function() {
		showTradingPeriodAlert($(this).parent().parent().parent());
	});
	
	$('.tradingperiod .ui-datepicker-trigger', awesomeform).livequery('click', function() {
		showTradingPeriodAlert($(this).parent().parent().parent());
	});
	
	$('.tradingperiod', awesomeform).livequery('click', function() {
		showTradingPeriodAlert($(this));
	});
	
	$('.validationalerttradingperiod').removeClass('validationalerttradingperiod').addClass('validationalerttradingperiodjscript');
	
	function showTradingPeriodAlert(tradingperiod)
	{
		thistradingperiodid=getID(tradingperiod.attr('id'));
		
		//don't change anything if we've refocussed on an input
		// in the currently focessed trading period (e.g. day/month/year selects)
		if (thistradingperiodid==focussedtradingperiodid)
			return;
	
		clearAlerts();
		focussedinputlineid=0;
	
		var position=tradingperiod.position();
		focussedtradingperiodid=thistradingperiodid;
		var validationalert=$('#validationalerttradingperiod_'+focussedtradingperiodid, awesomeform);

		if (0!=validationalert.length)
		{
			validationalert.css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}		
		else if (0!=$('#focusalerttradingperiod_'+focussedtradingperiodid, awesomeform).length)
		{
			tradingperiod.addClass('focussedtradingperiod');
			$('#focusalerttradingperiod_'+focussedtradingperiodid, awesomeform).css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
		}
	}
	
  /************ trading prices alerts *************/
  
  $('.tradingprice select', awesomeform).livequery('focus', function() {
    showTradingpriceAlert($(this).parent().parent().parent());
  });
  
  $('.tradingprice .ui-datepicker-trigger', awesomeform).livequery('click', function() {
    showTradingpriceAlert($(this).parent().parent().parent());
  });
  
  $('.tradingprice', awesomeform).livequery('click', function() {
    showTradingpriceAlert($(this));
  });
  
  $('.validationalerttradingprice').removeClass('validationalerttradingprice').addClass('validationalerttradingpricejscript');
  
  function showTradingpriceAlert(tradingprice)
  {
    thistradingpriceid=getID(tradingprice.attr('id'));
    
    //don't change anything if we've refocussed on an input
    // in the currently focessed trading price (e.g. day/month/year selects)
    if (thistradingpriceid==focussedtradingpriceid)
      return;
  
    clearAlerts();
    focussedinputlineid=0;
  
    var position=tradingprice.position();
    focussedtradingpriceid=thistradingpriceid;
    var validationalert=$('#validationalerttradingprice_'+focussedtradingpriceid, awesomeform);

    if (0!=validationalert.length)
    {
      validationalert.css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
    }   
    else if (0!=$('#focusalerttradingprice_'+focussedtradingpriceid, awesomeform).length)
    {
      tradingprice.addClass('focussedtradingprice');
      $('#focusalerttradingprice_'+focussedtradingpriceid, awesomeform).css({'top':position.top,'left':position.left+alertleftoffset}).fadeIn(alertfadeinspeed);
    }
  }	
  
	function clearAlerts()
	{
		$('.inputline', awesomeform).removeClass('focussedinputline');
		$('.focusalert', awesomeform).fadeOut(alertfadeoutspeed);
		$('.validationalertjscript', awesomeform).fadeOut(alertfadeoutspeed);
		
		$('.tradingperiod', awesomeform).removeClass('focussedtradingperiod');
		$('.focusalerttradingperiod', awesomeform).fadeOut(alertfadeoutspeed);
		$('.validationalerttradingperiodjscript', awesomeform).fadeOut(alertfadeoutspeed);
		
    $('.tradingprice', awesomeform).removeClass('focussedtradingprice');
    $('.focusalerttradingprice', awesomeform).fadeOut(alertfadeoutspeed);
    $('.validationalerttradingpricejscript', awesomeform).fadeOut(alertfadeoutspeed);
    
		$('#bidsubmission .inputcell', awesomeform).removeClass('focussedinputline');
	}
	
	function showHelper()
	{
		// clear all alerts first
		clearAlerts();
		
		$("#formhelper").fadeIn(alertfadeinspeed);
	}
	
	/*********************** date picker ***************************************/
	/*
		you'll probably want to share your datepicker functions between this and trading.js
		I've not done anything sensible with them, just hacked them a bit to make the
		fields display enough to style them
	*/
	
	wfd_setup_datepicker('dates_3');
	wfd_setup_datepicker('dates_4');
	wfd_setup_datepicker('dates_6');
	wfd_setup_datepicker('new_trading_1_start_date');
	wfd_setup_datepicker('new_trading_2_start_date');
	wfd_setup_datepicker('new_trading_3_start_date');

	/*********************** submit line for <a> actions ***********************/
	  
    /* some forms have multiple submit buttons, might as well do the same for them all */

    var buttonClasses = "button fullonbutton javascriptsubmit";
  
    $("div.submitline input[type='submit']").each( function() {
      var newLink = document.createElement("a");
        
      $(newLink).text($(this).val());
      $(newLink).attr("class", buttonClasses);
      
      if ($(this).parent().parent().parent().attr("id") != "signin")
        $(this).parent().append(newLink);
        
      $(this).remove();
    }); 
  
    $("div.submitline a:last").attr("class", $("div.submitline a:last").attr("class") + " lastbutton");
  
    var formActionInput = document.createElement("input");
    formActionInput.setAttribute("name", "formaction");
    formActionInput.setAttribute("type", "hidden");
    $('div.submitline').append(formActionInput);
  
    $("a.javascriptsubmit").live("click", function() {
        
      var action = $(this).text().toLowerCase();
      $("div.submitline input[name='formaction']").val(action);
      $("#awesomeform form:first").submit();
        
      return false;
    });
    
    $("#inner-rightcol div#registrationlogin input[type='submit']").each( function() {
        var newLink = document.createElement("a");
        
        $(newLink).text($(this).val());
        $(newLink).attr("class", buttonClasses);
        
        if ($(this).parent().parent().parent().attr("id") != "signin")
          $(this).parent().append(newLink);
          
        $(this).remove();
    });
    $("#inner-rightcol div#registrationlogin a:last").attr("class", $("div.submitline a:last").attr("class") + " lastbutton");
    
    $("#inner-rightcol div#registrationlogin a.javascriptsubmit").click(function() {
        
        var action = $(this).text().toLowerCase();
        $("#inner-rightcol div#registrationlogin input[name='formaction']").val(action);
        $("form#registrationsignin").submit();
          
        return false;
    });
    
    var buttonClasses = "button fullonbutton javascriptsubmit";
    
    $("div.fieldsetsubmitline input[type='submit']").each( function() {
      var newLink = document.createElement("a");
        
      $(newLink).text($(this).val());
      $(newLink).attr("class", buttonClasses);
        
      $(this).parent().append(newLink);
        
      $(this).remove();
    }); 
  
    $("div.fieldsetsubmitline a:last").attr("class", $("div.fieldsetsubmitline a:last").attr("class") + " lastbutton");
  
    var formActionInput = document.createElement("input");
    formActionInput.setAttribute("name", "formaction");
    formActionInput.setAttribute("type", "hidden");
    $('div.fieldsetsubmitline').append(formActionInput);
  
    $(".fieldsetsubmitline a.javascriptsubmit").live("click", function() {
        
      var action = $(this).text().toLowerCase();
      $("div.fieldsetsubmitline input[name='formaction']").val(action);
      $("#awesomeform form:first").submit();
        
      return false;
    });


    // and do the same for fieldset buttons too
    var buttonClasses = "button fullonbutton";
    
    $("div.fieldsetbuttons button").each( function() {
      var newLink = document.createElement("a");
      
      existingClass = $(this).attr("class");
      
      $(newLink).text($(this).text());
      $(newLink).attr("class", buttonClasses + " " + existingClass);
      $(newLink).attr("id", $(this).attr("id"));
        
      $(this).parent().append(newLink);
        
      $(this).remove();
    }); 
  
    $("div.fieldsetbuttons").each (function() {
    	$("a:last", $(this)).attr("class", $("a:last", $(this)).attr("class") + " lastbutton");
    });
    
    

    
    /*********************** datepicker style niceness *****************/
    
    $(".dateinputline").each( function() {
    	$("select:first", this).attr("class", "day");
    });
    $(".tradingperiods .datecell").each( function() {
    	$("select:first", this).attr("class", "day");
    });
});


function wfd_setup_datepicker(theid)
{
	
	jQuery("#"+theid+"_jquery_control").datepicker(jQuery.extend({}, {
	      minDate:    new Date(2009, 1 - 1, 1),
	      maxDate:    new Date(2024, 12 - 1, 31),
	      beforeShow: function(date){
				jQuery("#"+theid+"_jquery_control").val(jQuery("#"+theid+"_year").val() + "-" + jQuery("#"+theid+"_month").val() + "-" + jQuery("#"+theid+"_day").val());
				return {};
			},
	      onSelect:   function(date){
				wfd_update_linked(theid, date, this);			
			},
	      showOn:     "button",
	      buttonImage: 'images/icon-datepicker.gif',
		buttonImageOnly: true
	      
	}, jQuery.datepicker.regional["en_GB"], {}, {dateFormat: "yy-mm-dd"}));
	
	jQuery("#"+theid+"_day, #"+theid+"_month, #"+theid+"_year").live('change',function(){
		wfd_check_linked_days(theid);
	}); 
}

/**
 * 
 * This function is called when the user selects a date using the jquery date picker
 * 
 * It updates the select boxes with the selected values.
 * 
 * @param theid
 * @param date
 * @param domobject
 * @return
 */
function wfd_update_linked(theid, date, domobject)
{
	var day = date.substring(8);
	var month = date.substring(5, 7);
	var year = date.substring(0, 4)
	
	var oStartDate = new Date(year, month - 1, day);
	var durationselector = theid.replace(/_start_date/gi, '');
	
	var duration = parseInt($("#"+durationselector+"_duration").val());
	
	if(duration > 0)
	{
		//Remove this period from the hash table;
		var rowtime = parseInt($('td:first',$(domobject).parent().parent()).text());
		delete oTradingPeriods[rowtime];
		if(validate_trading_period_dates(domobject, day, month, year, duration))
		{
		
			//Set this rows date time stamp
			$('td:first',$(domobject).parent().parent()).text(oStartDate.getTime()/1000);
			//Re-sort the table
			sort_trading_table($(domobject).parent().parent(), parseInt(oStartDate.getTime()/1000));
			
			jQuery("#"+theid+"_year").val(year);
			jQuery("#"+theid+"_month").val(month);
			jQuery("#"+theid+"_day").val(day);
		}
		
		update_trading_periods_hash();
	}
	else
	{
		jQuery("#"+theid+"_year").val(year);
		jQuery("#"+theid+"_month").val(month);
		jQuery("#"+theid+"_day").val(day);
		
	}
}