/*
**
** Filename	: jquery.manheim.connect2.js
** 
** Description	: Provides the connect panel for the front page
** 
** Usage:
** 
** $Id: jquery.manheim.connect2.js,v 1.12 2010-07-16 12:14:41 rshaw Exp $
*/

/*
** Deprecated?
function Set_AdvList_Sale_Count(n) {
	jQuery('#advsearch_sale_count').html(n);
}
*/

// Accordion handlers
jQuery.manheimConnect = {


	// Links used to populate the accordions
	accord_poplinks: {
		sale_variant:        '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dsale_variant',
		vehicle_type_desc:   '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dvehicle_type_desc',
		make:                '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dmake',
		model:               '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dmodel',
		subseries:           '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dsubseries',
		body_style_desc:     '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dbody_style_desc',
		displacement:        '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Ddisplacement',
		fuel_type_name:      '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dfuel_type_name',
		transmission_name:   '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dtransmission_name',
		age_class:           '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dage_class',
		odometer_label:      '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dodometer_label',
		mileage_class:       '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dmileage_class',
		auction_name:        '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dauction_name',
		consignor_name:      '?rm=panel;Connect2=rm%3Dpopulate_tab%3Btab%3Dconsignor_name'
	},

	// Links used to populate the accordions
	s_initialExtraParam: '%3Bvehicle_type_desc%3DCar',
	b_initialCall: true,

	a_accPopParams: {},
	a_accDepCrit:{},
	a_accDepCritOld:{},
	a_accHeader: {},


	s_accHeadOnUrl:  "?rm=panel;Connect2=rm%3Daccheader_only_on",
	s_accHeadOffUrl: "?rm=panel;Connect2=rm%3Daccheader_only_off",

	//s_summUpdOnUrl:  "?rm=summary_only_on",
	//s_summUpdOffUrl: "?rm=summary_only_off",

	s_accFooterOnUrl:  "?rm=panel;Connect2=rm%3Daccheader_only_on",
	s_accFooterOffUrl: "?rm=panel;Connect2=rm%3Daccheader_only_off",

	i_accSem: {},

	s_critSumm: "",
	s_accClicked: "",
	s_accOpen: "",
	s_accRemClicked: "",

	time_lastChanged: 250,
	time_updateAperture: 120000,
	i_retryMax: 50,			// This mult. by time_lastChanged is the internal network timeout value
	dat_lastChanged: null,
	i_updatesRunningSem: 0,
	b_updateSummary: false,



	initialize: function()
	{


		/* Stops the init being called for search panel pages */
		if(jQuery("#advsearch_accord_div").length==0)
		{
			return;
		} 

		jQuery.manheimConnect.i_updatesRunningSem=0;



		jQuery("#advsearch_accord_div").accordion(
			{
				active: true,
				autoHeight: false,
				collapsible: true,
				header: 'h3'
			}
		);

		/* init the accord */

		jQuery("#advsearch_accord_div h3").click(function(e)
		{

			var clicked = $(this).next("div").attr('id');


			jQuery('a.ad-minus').removeClass('current');
			jQuery(this).children('a.ad-minus').addClass('current');

			jQuery(this).children('a.ad-minus').toggleClass('minus-button').toggleClass('add-button');
			jQuery('a.minus-button:not(.current)').addClass('add-button').removeClass('minus-button');

			//jQuery(this).children('a.remove-button').toggle();


			if(jQuery.manheimConnect.s_accOpen==clicked)
			{
				jQuery.manheimConnect.s_accOpen="";
				jQuery.manheimConnect.s_accClicked="";
			}
			else
			{
				jQuery.manheimConnect.s_accClicked=clicked;
				jQuery.manheimConnect.s_accOpen=clicked;
			}

			jQuery.manheimConnect.procCriteria('check');
			this.blur();
		});

		jQuery.each(this.accord_poplinks,
			function(i, getUrl)
			{
				jQuery.manheimConnect.a_accPopParams[i]="";
				jQuery.manheimConnect.a_accDepCrit[i]="";
				jQuery.manheimConnect.a_accDepCritOld[i]="";
				jQuery.manheimConnect.a_accHeader[i]="";
				jQuery.manheimConnect.i_accSem[i]=0;
				jQuery.manheimConnect.s_curAccord="";

				var remButName='#'+i+'_remove';


				// Set the click events on the accord buttons
				jQuery(remButName).click(
					function(e)
					{
						jQuery('#'+i+' input:checkbox:checked').each(
							function(par_iter,par_val)
							{
								this.checked=false;
							}
						);
						jQuery.manheimConnect.s_accRemClicked=i;
						jQuery.manheimConnect.procCriteria('check');
					}
				);
			}
		);
		this.procCriteria('restore');
		this.connectUpdateTimer();


	},

	SetTimer: function()
	{
		jQuery.manheimConnect.dat_lastChanged=(new Date()).getTime();
	},

	
	/*
	** connectUpdateTimer:
	**
	**
	** Controls the background timer
	** 
	** Passed in: p_accord
	** Returned byref: 
	**
	*/
    connectUpdateTimer: function()
	{
		var b_returnVal=true;
		if (jQuery.manheimConnect.dat_lastChanged != null)
		{
			var curTime= (new Date()).getTime();
			var timeDiff= curTime - jQuery.manheimConnect.dat_lastChanged;


			if (timeDiff >= jQuery.manheimConnect.time_updateAperture)
			{
				i_returnVal=jQuery.manheimConnect.procCriteria('force');
				jQuery.manheimConnect.SetTimer();
			}
			else if(timeDiff >= jQuery.manheimConnect.time_lastChanged)
			{
				i_returnVal=jQuery.manheimConnect.procCriteria('check');
				jQuery.manheimConnect.SetTimer();
			}
		}
		// Set our internal repr. of the timer position.
		jQuery.manheimConnect.SetTimer();
		window.setTimeout(
			function()
			{
				jQuery.manheimConnect.connectUpdateTimer()
			},
			jQuery.manheimConnect.time_lastChanged
		);
    },

	//
	// timer event callback for accordion checkboxes
	//
	// Periodically called to check the accordion states and updates the trimmings.
	// 
	// Updates:
	//  links to search
	//  accordion "remove" button
	//  summary search panel
	//
	procCriteria: function(p_action)
	{
		var s_summaryParams="";
		var b_returnVal=false;

		if(p_action=='restore')
		{
			var i_nParams=jQuery.manheimConnect.updateAccords(p_action);
		}

		if(p_action=='force')
		{
			// Set the state of the data object so that it updates all accords.
			jQuery.manheimConnect.forceUpdate();
		}
		if(p_action!="restore")
		{
			jQuery.manheimConnect.updateAccords(p_action);
		}

		return true;


	},	//  procCriteria(p_accord,p_searchCrit,cb)


	/*
	** readCriteria:
	**
	** 
	**
	** Passed in: p_accord
	** Returned byref: p_accChecks,p_accParams
	**
	** p_accChecks are the checks in the passed accord section
	** p_accParams are the params required to populate the passed accord (summ of previous accords)
	*/

	readCriteria: function(p_searchString,p_accName)
	{
		var accHeader="";
		var accChecks="";
		var accCritParam;
		var paramCount=0;

		jQuery(p_searchString).each
		(
			function(par_iter,par_val)
			{
				if(par_val.checked == true)
				{
					if(! par_val.value.match("rm"))
					{
						if(accHeader == "")
						{
							accHeader=par_val.value;
						}
						else
						{
							accHeader+=', '+par_val.value;
						}

						accChecks=accChecks+"%3B"+p_accName+"%3D"+par_val.value;
						paramCount++;
					}
				}
			}
		);
/*	if(accChecks=="")
		{
			accChecks=p_prevCrit;
		}*/

		// Only update the list of details in the accord header if the ajax isnt running
		if(!this.isRunning())
		{
			jQuery.manheimConnect.a_accHeader[p_accName]=accHeader;
			if(jQuery.manheimConnect.a_accHeader[p_accName] != "")
			{
				jQuery('#'+p_accName+'_headinfo').html('('+jQuery.manheimConnect.a_accHeader[p_accName]+')');
				jQuery('#'+p_accName+'_remove').show();
			}
			else
			{
				jQuery('#'+p_accName+'_headinfo').html('');
				jQuery('#'+p_accName+'_remove').hide();
			}
		}
		else
		{
			if(jQuery.manheimConnect.a_accHeader[p_accName] != "")
			{
				jQuery('#'+p_accName+'_headinfo').html('(...)');
			}
		}

		// Prepopulate with "Car" in vehicle_type_desc
		if(jQuery.manheimConnect.b_initialCall == true && p_accName == 'vehicle_type_desc')
		{
			accChecks+=this.s_initialExtraParam;
		}
		jQuery.manheimConnect.a_accPopParams[p_accName]=accChecks;
		jQuery.manheimConnect.a_accHeader[p_accName]=accHeader;

		return paramCount;
	},

	// Connect Panel does not farm params from hidden fields.

	/*
	** farmAccords:
	**
	**
	** Reads params from hidden fields
	** 
	** Apes farmAccords.
	**
	** Passed in: p_accord
	** Returned byref: p_accChecks,p_accParams
	**
	** p_accChecks are the checks in the passed accord section
	** p_accParams are the params required to populate the passed accord (summ of previous accords)
	*/

	farmAccords: function()
	{
		var totCrit="";
		var paramCount=0;
		// Drive the loop with what we expect to be there

		jQuery.each(this.accord_poplinks,
			function(p_critName, p_param)
			{

				// This is diff in the panel code - here it is one level lower.
				jQuery.manheimConnect.readCriteria('#'+ p_critName+' input:checkbox',p_critName);
				totCrit+=jQuery.manheimConnect.getCrit(p_critName);
			}

		);

		// Populate all the deps with the complete search string
		// (legacy construct to implement independent dependencies between the panels,
		// 		left in as its easier)

		jQuery.each(this.accord_poplinks,
			function(p_critName, p_param)
			{
				// Previously populated in readCriteria, panel by panel 
				jQuery.manheimConnect.a_accDepCrit[p_critName]=totCrit;
			}

		);
		// Overall summary criteria (now same as panel crit)
		jQuery.manheimConnect.s_critSumm=totCrit;



		return;
	},
	/*
	** setOldAccordParam:
	**
	**
	** Reads crit
	** 
	**
	** Passed in: p_accord
	**
	*/

	setOldAccordParam: function(p_accName)
	{
		this.a_accDepCritOld[p_accName]=this.a_accDepCrit[p_accName];
	},

	/*
	** forceUpdate:
	**
	**
	** Reads crit
	** 
	**
	** Passed in: p_accord
	**
	*/

	forceUpdate: function()
	{

		jQuery.each(this.accord_poplinks,
			function(p_critName, p_param)
			{

				jQuery.manheimConnect.a_accDepCritOld[p_critName]="RESET";
				jQuery.manheimConnect.s_critSumm="RESET";
			}
		);
		jQuery.manheimConnect.b_updateSummary=true;
	},

	/*
	** isReadyForUpdate:
	**
	**
	** Reads crit
	** 
	**
	** Passed in: p_accord
	**
	*/
	isReadyForUpdate: function(p_accName)
	{
		return (jQuery.manheimConnect.a_accDepCrit[p_accName]!=jQuery.manheimConnect.a_accDepCritOld[p_accName]);
	},




	/*
	** getCrit:
	**
	**
	** Reads crit
	** 
	**
	** Passed in: p_accord
	**
	*/

	getCrit: function(p_accName)
	{
		if(this.a_accPopParams[p_accName]!=null)
		{
			return this.a_accPopParams[p_accName];
		}
		else
		{
			return "";
		}
	},

	/*
	** isRunning:
	**
	**
	** Process semaphores
	** 
	**
	** Passed in: 
	**
	*/
	isRunning: function()
	{

		var b_retVal=false;
		jQuery.each(jQuery.manheimConnect.i_accSem,
			function(i, semVal)
			{
				if(jQuery.manheimConnect.i_accSem[i]>0)
				{
					b_retVal=true;
					if(jQuery.manheimConnect.i_accSem[i] > jQuery.manheimConnect.i_retryMax)
					{
						jQuery.manheimConnect.i_accSem[i]=0;
					}
					// "break" the "each"
					return false;
				}
			}
		);
		return b_retVal;
	},

	/*
	** updateAccords:
	**
	**
	** Reads crit
	** 
	**
	** Passed in: p_accord
	**
	*/
	updateAccords:function(p_action)
	{
		var i_returnVal=0;
		if(! this.isRunning())
		{
			var curOpen=jQuery.manheimConnect.s_accOpen;
			var curClicked=jQuery.manheimConnect.s_accClicked;
			var remClicked=jQuery.manheimConnect.s_accRemClicked;

			// Re-read the page state on 'force' and 'check'
			if(p_action!='restore')
			{
				jQuery.manheimConnect.farmAccords(p_action);
			}
			else // Set the default value on first entry
			{
				i_returnVal=jQuery.manheimConnect.farmAccords(p_action);
				jQuery.manheimConnect.b_initialCall=false;
				curClicked='vehicle_type_desc';
			}

			// Hacks to re-implement dependency
			var b_afterCurrentAcc=false;
			var b_removeClicked=false;

			if(remClicked!="")
			{
				if(curOpen!="")
				{
					curClicked=curOpen;
				}
				else
				{
					curClicked=remClicked;
				}
				jQuery.manheimConnect.s_accRemClicked="";
			}
			if(curClicked!="")
			{
				jQuery.manheimConnect.i_accSem[curClicked]++;
				jQuery.manheimConnect.i_updatesRunningSem++;



				jQuery('#'+curClicked).html('Please wait...');
				jQuery.manheimConnect.SetTimer();



				var checkCount=jQuery('#'+curClicked+' input:checkbox:checked').length;


				jQuery.manheimConnect.b_updateSummary=true;
				jQuery.manheimConnect.s_accClicked="";
				jQuery.manheimConnect.setOldAccordParam(curClicked);


				jQuery.get(jQuery.manheimConnect.s_accHeadOffUrl,
					function(offData)
					{
						jQuery('#advsearch_accheader_div').html(offData);
						jQuery('#advsearch_accfooter_div').html(offData);

						jQuery.get(
							jQuery.manheimConnect.accord_poplinks[curClicked] + jQuery.manheimConnect.a_accDepCrit[curClicked],
							function(data)
							{ 
								jQuery('#'+curClicked).html(data);

								var tmpParam;

								tmpParam=jQuery.manheimConnect.s_critSumm;

								jQuery.get(jQuery.manheimConnect.s_accHeadOnUrl+tmpParam,
									function(onData)
									{ 
										jQuery('#advsearch_accheader_div').html(onData);
										jQuery('#advsearch_accfooter_div').html(onData);
										jQuery.manheimConnect.i_accSem[curClicked]--;
										jQuery.manheimConnect.i_updatesRunningSem--;
										jQuery.manheimConnect.SetTimer();
									}
								);
							}
						);
					}
				);

			}
			else if(curOpen!="")
			{
				if(jQuery.manheimConnect.isReadyForUpdate(curOpen))
				{
					jQuery.manheimConnect.setOldAccordParam(curOpen);
					var tmpParam=jQuery.manheimConnect.s_critSumm;

					jQuery.get(jQuery.manheimConnect.s_accFooterOnUrl+tmpParam,
						function(onData)
						{
							jQuery('#advsearch_accfooter_div').html(onData);
							jQuery('#advsearch_accheader_div').html(onData);
						}
					);
				}
			}
		}

		return i_returnVal;
	},


	/*
	** Dump the criteria tables
	*/
	dumpCritParams: function()
	{

		console.log("dumpCritParams:vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
		// Dump em all at once
		jQuery.each(this.accord_poplinks,
			function(p_critName,p_critParam)
			{
				console.log("dumpCritParams:accPopParams ["+p_critName+"]["+jQuery.manheimConnect.a_accPopParams[p_critName]+"]");
				console.log("dumpCritParams:accHeader    ["+p_critName+"]["+jQuery.manheimConnect.a_accHeader[p_critName]+"]");
				console.log("dumpCritParams:accDepCrit   ["+p_critName+"]["+jQuery.manheimConnect.a_accDepCrit[p_critName]+"]");
				console.log("dumpCritParams:accDepCritOld["+p_critName+"]["+jQuery.manheimConnect.a_accDepCritOld[p_critName]+"]");
				console.log("dumpCritParams:accSem       ["+p_critName+"]["+jQuery.manheimConnect.i_accSem[p_critName]+"]");

			}
		);
		console.log("dumpCritParams:^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");

		return;

	}
}


