var as_location_name = false;

var hashChangeBusy = false;

/**

 * Ajax Queue Plugin

 */

(function($) {

    var ajax = $.ajax;

    var pendingRequests = {};



    $.ajax = function(settings) {

        settings = jQuery.extend(

            settings,

            jQuery.extend(

                {},

                jQuery.ajaxSettings,

                settings

            )

        );

        var port = settings.port;



        switch(settings.mode) {

            case "abort":

                if ( pendingRequests[port] ) {

                    pendingRequests[port].abort();

                }

                return pendingRequests[port] = ajax.apply(this, arguments);



            case "queue":

                var _old = settings.complete;

                settings.complete = function(){

                    if ( _old )

                        _old.apply( this, arguments );

                    jQuery([ajax]).dequeue("ajax" + port );

                };



                jQuery([ ajax ]).queue("ajax" + port, function(){

                    ajax( settings );

                });

                return;



            case "dequeue":

                jQuery([ajax]).dequeue("ajax" + port );



                if(jQuery.isFunction(settings.complete))

                    settings.complete(settings);



                return;

        }



        return ajax.apply(this, arguments);

    };

})($jqPmSearch);



var ASFormOptions = {

	beforeSubmit:  showAsRequest,

	success     :   showAsResponse,

	dataType	:   'json',

	mode		:   'abort',

	port		:	'asSearch',

	data		: { ajaxMode:1 }

};

var ASFormDynamicCrtiterionOptions = {

		beforeSubmit:  showAsRequest,

		success     :   showAsResponse,

		dataType	: 'json',

		mode		:  'abort',

		port		:	'asSearch',

		data		: { with_product: 0,ajaxMode:1 }

};

var ASFormOptionsReset = {

		beforeSubmit:   showAsRequest,

		success     :   showAsResponse,

		dataType	: 'json',

		mode		:  'abort',

		port		:	'asSearch',

		data		: { reset:1,ajaxMode:1 }

	};

var ASFormDynamicCrtiterionOptionsReset = {

		beforeSubmit:  showAsRequest,

		success     :   showAsResponse,

		dataType	: 'json',

		mode		:  'abort',

		port		:	'asSearch',

		data		: { with_product: 0,reset:1,ajaxMode:1 }

};



// pre-submit callback

function showAsRequest(formData, jqForm, options) {

    var queryString = $.param(formData);

    var id_search = $jqPmSearch(jqForm).find('input[name=id_search]').val();

    setlayer('body', '#PM_ASBlockOutput_'+id_search,'PM_ASearchLayerBlock','PM_ASearchLayerBlock');

    return true;

}



var asLayers = new Array();

function setlayer(parent, element,elementId,elementClass) {

	if(!$(element).filter(":visible").length) removelayer(elementId);

	var blockWidth = $(element).outerWidth();

	var blockHeight = $(element).outerHeight();

	var blockTop = $(element).offset().top;

	var blockLeft = $(element).offset().left;



	if(!$('#'+elementId).length)

		$('body').append('<div id="'+elementId+'" class="'+elementClass+'"><iframe src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" style="position:absolute; left:0; top:0px; display:block; filter:alpha(opacity=0);width:'+blockWidth+'px;height:'+blockHeight+'px" ></iframe></div>');



	$('#'+elementId).css({

		width:blockWidth+'px',

		height:blockHeight+'px',

		top:blockTop+'px',

		left:blockLeft+'px',

		position:'absolute',

		zIndex:'1000'

	});

	$('#'+elementId).fadeTo('fast',0.8);

	if(typeof(asLayers[elementId]) == 'undefined')

		asLayers[elementId] = setInterval(function() {setlayer(parent, element,elementId,elementClass)}, 300);

}

function removelayer(elementId) {

	clearInterval(asLayers[elementId]);

	delete asLayers[elementId];

	if($('#'+elementId).length) {

		$('#'+elementId).fadeOut('fast',function() {

			$(this).remove();



		});

	}

}



function setResultsContents(id_search,htmlResults) {

	var oldBreadCrump = $jqPmSearch('#center_column .breadcrumb').html();

	setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');

	var addToHeight = 0;

	if(ASParams[id_search].keep_category_information) {

	  var addheight = true;

	  $jqPmSearch('#productsSortForm, #pagination, .pagination, #PM_ASearchResultsInner, #PM_ASearchResults, #center_column form, #center_column script, #product_list').remove();

	  $jqPmSearch('#center_column').css('height','auto');

	  addToHeight = $jqPmSearch('#center_column').outerHeight();

	}

	var htmlResultsHeight = $jqPmSearch('<div style="width:'+$jqPmSearch('#center_column').outerWidth()+'px;">'+htmlResults+'</div>').actual( 'innerHeight', { clone : true })+addToHeight+20;

	$jqPmSearch('body #center_column').animate({

	    height: htmlResultsHeight+'px'

	  }, 500, function() {

	      // Animation complete.

		  $jqPmSearch('body #center_column').css('height','auto');

		  if(ASParams[id_search].keep_category_information) {

			  if($jqPmSearch('#PM_ASearchSeoCrossLinks').length)

				  $jqPmSearch(htmlResults).insertBefore('#PM_ASearchSeoCrossLinks');

			  else

				  $jqPmSearch('#center_column').append(htmlResults);

		  }

		  else $jqPmSearch('#center_column').html(htmlResults);



		  removelayer('PM_ASearchLayerResult');

	});

	//Make animation separetly, because callback function is exec two time if i USE $jqPmSearch('body #center_column, body #PM_ASearchLayerResult') selector

	$jqPmSearch('body #PM_ASearchLayerResult').animate({

	    height: htmlResultsHeight+'px'

	}, 450);

}

function showAsResponse(responseText, statusText, xhr, $form)  {



	var id_search = $form.find('input[name=id_search]').val();

	setTimeout( function() {

		changeHash(id_search);

	},500);

	var step_search = $form.find('input[name=step_search]').val();

	var hookName = $form.find('input[name=hookName]').val();

	if(responseText.html_block) {

		var htmlBlock = responseText.html_block;

		step_search = false;

	}

	else if(step_search) {

		var next_id_criterion_group = $form.find('input[name=next_id_criterion_group]').val();

		var htmlBlock = responseText.html_criteria_block;

	}

	var htmlResults = responseText.html_products;

	if(htmlBlock) {

		if(hookName == 'top') {

			 if(!step_search) {

				 $jqPmSearch('#PM_ASBlockOutput_'+id_search).html(htmlBlock);

				 removelayer('PM_ASearchLayerBlock');

			  }else {

				  var htmlBlockSelection =  responseText.html_selection_block;

				  if(htmlBlockSelection) {

					  $jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASSelectionsBlock').html(htmlBlockSelection);



				  }

				  $jqPmSearch('#PM_ASCriterionsGroup_'+id_search+'_'+next_id_criterion_group).html(htmlBlock);

				  removelayer('PM_ASearchLayerBlock');

			  }

		}

		else {

			  // Animation complete.

			  if(!step_search) {

				  $jqPmSearch('#PM_ASBlockOutput_'+id_search).html(htmlBlock);

				  removelayer('PM_ASearchLayerBlock');

			  }else {

				  var htmlBlockSelection =  responseText.html_selection_block;

				  if(htmlBlockSelection) {

					  $jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASSelectionsBlock').html(htmlBlockSelection);



				  }

				  $jqPmSearch('#PM_ASCriterionsGroup_'+id_search+'_'+next_id_criterion_group).html(htmlBlock);

				  removelayer('PM_ASearchLayerBlock');

			  }

		}



	}

	if(htmlResults) {

		setResultsContents(id_search,htmlResults);

	}

}

function initNotMulticriteriaElements()  {

	$jqPmSearch('.PM_ASNotMulticriteria').unbind('mousedown.eventNotMulticriteriaElements').bind('mousedown.eventNotMulticriteriaElements',function() {

		if($jqPmSearch(this).parents('li').hasClass('PM_ASCriterionDisable')) return;

		//For checkbox

		if($jqPmSearch(this).attr('type') == 'checkbox') {

			if(!$jqPmSearch(this).attr('checked')) {

				var curIndex = $jqPmSearch(this).parent('li').index();

				$jqPmSearch(this).parent('li').parent('ul').find('li:not(:eq('+curIndex+')) > input[type=checkbox]').removeAttr('checked');

			}

		} else {

			if(!$jqPmSearch(this).hasClass('PM_ASCriterionLinkSelected')) {

				var curIndex = $jqPmSearch(this).parent('li').index();

				$jqPmSearch(this).parent('li').parent('ul').find('li:eq('+curIndex+') > input[type=hidden]').attr('disabled','');

				$jqPmSearch(this).parent('li').parent('ul').find('li:not(:eq('+curIndex+')) > input[type=hidden]').attr('disabled','disabled');

				$jqPmSearch(this).parent('li').parent('ul').find('li > a').removeClass('PM_ASCriterionLinkSelected');

			}

		}

	});

}

function initToogleBloc()  {

	if($jqPmSearch('.PM_ASBlockOutputHorizontal').find('.PM_ASCriterionHide').length) {

		$jqPmSearch('.PM_ASBlockOutputHorizontal').find('.PM_ASCriterionsGroup').each(function(){

			// add greg 2012-01-11
			var nom_id = $jqPmSearch(this).attr("id");
			//PM_ASCriterionGroupImage_2_16
			//PM_ASCriterionsGroup_2_16
			nom_id = nom_id.replace("PM_ASCriterionsGroup_","PM_ASCriterionGroupImage_");
			//alert( nom_id );
			/*var num_max = 0;
			if( $jqPmSearch('ul#'+nom_id).length > num_max  ){
				num_max = $jqPmSearch('ul#'+nom_id).length;
			}*/
			var num_total = 0;
			var hauteur = 0;
			var i = 0;
			$jqPmSearch('ul#'+nom_id+" li").each(function(){
				num_total++;
				i++;
				if( i == 1 ){
					hauteur += 34;
				}else if( i == 4 ){
					i = 0;
				}
				
			});
			//alert(hauteur);
			hauteur += 20;
			
			 $jqPmSearch(this).css('height',hauteur);
			 //$jqPmSearch(this).css('height',$jqPmSearch(this).height());

			 $jqPmSearch(this).find('.PM_ASCriterionsOutput').css('position','absolute');

		});

	}

}

function initFormSearchBlocLink(id_search)  {

	$jqPmSearch(function() {

		$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASSelections').find('.PM_ASSelectionsRemoveLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

			$jqPmSearch(this).next('input').attr('disabled','disabled');

			$jqPmSearch(this).parents('form').ajaxSubmit(ASFormOptions);

		});

	});

	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionLink').unbind('click.eventFormSearchLink').bind('click.eventFormSearchLink',function() {

		if($jqPmSearch(this).parents('li').hasClass('PM_ASCriterionDisable')) return;

		if(!$jqPmSearch(this).hasClass('PM_ASCriterionLinkSelected')) {

			$jqPmSearch(this).next('input').removeAttr('disabled');

			setTimeout( function() {

				$jqPmSearch(this).addClass('PM_ASCriterionLinkSelected');

			},100);

		} else {

			$jqPmSearch(this).next('input').attr('disabled','disabled');

			setTimeout( function() {

				$jqPmSearch(this).removeClass('PM_ASCriterionLinkSelected');

			},100);

		}

	});

	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleClick a').click(function() {

		$jqPmSearch(this).parents('.PM_ASCriterions').find('.PM_ASCriterionHide').slideToggle('fast');

		$jqPmSearch(this).children('.PM_ASHide, .PM_ASShow').toggle();

	});

	var criteriaOverTimer = {};
	
	/* ajout greg 2012-01-02 */
	//height_search = $jqPmSearch("div#PM_ASBlockOutput_2").css("height");
	//var height_search_2 = $jqPmSearch("div#PM_ASBlockOutput_2 div.block_content").css("height");

	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseenter(function() {
	//$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseover(function() {

		if(typeof(criteriaOverTimer[$(this).attr('id')]) != 'undefined' && criteriaOverTimer[$(this).attr('id')]) { clearTimeout(criteriaOverTimer[$(this).attr('id')]);criteriaOverTimer[$(this).attr('id')] = false;}
		
		/* ajout greg 2012-01-02 augmentation de la taille au survol */
		//alert( $jqPmSearch(this).parent(0).parent(0).height() );
		if( $jqPmSearch(this).parent(0).parent(0).height() > 180 ){
			$jqPmSearch("div#PM_ASBlockOutput_2").height(height_search_2);
		}

		$jqPmSearch(this).addClass('PM_ASCriterionGroupToogleHover');

		$jqPmSearch(this).find('.PM_ASCriterionHide').slideDown('fast');

		$jqPmSearch(this).find('.PM_ASCriterionHideToogleHover').hide();
		
		

	});

	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseleave(function() {
	//$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseout(function() {

		var element = $(this);

		criteriaOverTimer[$(this).attr('id')] = setTimeout( function() {

			$jqPmSearch(element).find('.PM_ASCriterionHide').slideUp('fast',function() {

				$jqPmSearch(this).parents('.PM_ASCriterions').removeClass('PM_ASCriterionGroupToogleHover');

			});

			$jqPmSearch(element).find('.PM_ASCriterionHideToogleHover').show();

		},200);
		
		var timer = setTimeout( function() {
			/* ajout greg 2012-01-02 diminution de la taille au survol */
			$jqPmSearch("div#PM_ASBlockOutput_2").css("height",height_search);
		},500);

	});

}

/* ajout greg 2012-01-02 remplissage variable hauteur a la creation */
var height_search;
var height_search_2;
$jqPmSearch(document).ready(function(){
	height_search = $jqPmSearch("div#PM_ASBlockOutput_2").css("height");
	height_search_2 = $jqPmSearch("div#PM_ASBlockOutput_2 div.block_content").height() + 10;
	//alert( height_search_2 );
});

function initFormSearchLink()  {

	$jqPmSearch(function() {

		$jqPmSearch('#center_column .PM_ASSelections').find('.PM_ASSelectionsRemoveLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

			$jqPmSearch(this).next('input').attr('disabled','disabled');

			$jqPmSearch(this).parents('form').ajaxSubmit(ASFormOptions);

		});

	});

}

function nextStep(id_search,e,submit,search_method,dynamic_criterion)  {

	var current_next_id_criterion_group_input = $jqPmSearch(e).parents('.PM_ASCriterionsGroup').next('.PM_ASCriterionsGroup').find('input:disabled[name=current_id_criterion_group]');

	if($jqPmSearch(current_next_id_criterion_group_input).length) {

		$jqPmSearch(e).parents('.PM_ASCriterionsGroup').nextAll('.PM_ASCriterionsGroup').children('.PM_ASCriterionsOutput').children('.PM_ASCriterions').children('.PM_ASCriterionsGroupOuter').children('.PM_ASCriterionStepEnable').html('').parent('.PM_ASCriterionsGroupOuter').children('.PM_ASCriterionStepDisable').show();

		$jqPmSearch('#PM_ASForm_'+id_search).find("input[name=next_id_criterion_group]").val($jqPmSearch(current_next_id_criterion_group_input).val());

	}



	setTimeout( function() {

		if(search_method == 2) {

			$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);

		}else {

			$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);

		}

	},100);

}

//Get AS URL because it may be incorrectly formatted

function getAsAjaxUrl(curUrl)  {

	var destUrl = curUrl;

	var asPathReg = new RegExp("("+ASPath+")","g");

	if (!destUrl.match(asPathReg)) {

		var asQuery = curUrl.substring(curUrl.indexOf("?",0));

		destUrl = ASPath+'advancedsearch4.php'+asQuery;

	}

	return destUrl;

}

function encodeAsParams(params)  {

	var reg1 = new RegExp("=", "g");

	var reg2 = new RegExp("as_criterions\\[", "g");

	var reg3 = new RegExp("id_search:", "g");

	var reg4 = new RegExp("&step_search:[0-9]+|&next_id_criterion_group:[0-9]+", "g");

	var reg5 = new RegExp("hookName:", "g");

	var reg6 = new RegExp("keep_category_information:", "g");

	var reg7 = new RegExp("orderby:", "g");

	var reg8 = new RegExp("orderway:", "g");

	var reg9 = new RegExp("id_category_search:", "g");

	var reg10 = new RegExp("as_price_range:", "g");

	var reg11 = new RegExp("id_manufacturer_search:", "g");

	var reg12 = new RegExp("id_supplier_search:", "g");





	params = params.replace(reg1,':');

	params = params.replace(reg2,'s[');

	params = params.replace(reg3,'sid:');

	params = params.replace(reg4,'');

	params = params.replace(reg5,'h:');

	params = params.replace(reg6,'k:');

	params = params.replace(reg7,'ob:');

	params = params.replace(reg8,'ow:');

	params = params.replace(reg9,'ics:');

	params = params.replace(reg10,'pr:');

	params = params.replace(reg11,'ims:');

	params = params.replace(reg12,'iss:');

	return params;

}

function decodeAsParams(params)  {

	var reg1 = new RegExp(":", "g");

	var reg2 = new RegExp("s\\[", "g");

	var reg3 = new RegExp("sid=", "g");

	var reg4 = new RegExp("^#", "g");

	var reg5 = new RegExp("&h=", "g");

	var reg6 = new RegExp("&k=", "g");

	var reg7 = new RegExp("&ob=", "g");

	var reg8 = new RegExp("&ow=", "g");

	var reg9 = new RegExp("&ics=", "g");

	var reg10 = new RegExp("&pr=", "g");

	var reg11 = new RegExp("&ims=", "g");

	var reg12 = new RegExp("&iss=", "g");



	params = params.replace(reg1,"=");

	params = params.replace(reg2,"as_criterions[");

	params = params.replace(reg3,"id_search=");

	params = params.replace(reg4,"");

	params = params.replace(reg5,'&hookName=');

	params = params.replace(reg6,'&keep_category_information=');

	params = params.replace(reg7,'&orderby=');

	params = params.replace(reg8,'&orderway=');

	params = params.replace(reg9,'&id_category_search=');

	params = params.replace(reg10,'&as_price_range=');

	params = params.replace(reg11,'&id_manufacturer_search=');

	params = params.replace(reg12,'&id_supplier_search=');

	return params;

}



function initSearchBlock(id_search,search_method,step_search,dynamic_criterion)  {

	if(typeof(ASHash[id_search]) == 'undefined') {

		var currentHash = decodeURIComponent($jqPmSearch('#PM_ASForm_'+id_search).serialize());

		currentHash = encodeAsParams(currentHash);

		ASHash[id_search] = currentHash;

	}



	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASResetSearch').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

		var regIdBack = new RegExp("\#.*", "g");

		var backUrl   = location.href.replace(regIdBack,'');

		location.href = backUrl;

	});

	if($jqPmSearch('.PM_ASSelectionsBlock .PM_ASSelectionsDropDownShowLink').length) {

		$jqPmSearch('.PM_ASSelectionsBlock .PM_ASSelectionsDropDownShowLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

			$jqPmSearch(this).next('.PM_ASSelectionsDropDownMenu').slideToggle('fast');

	    });

	}



	$jqPmSearch('#PM_ASForm_'+id_search+' .PM_ASCriterionLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

		if($jqPmSearch(this).parents('li').hasClass('PM_ASCriterionDisable')) return;

		if(step_search) {

			nextStep(id_search,$jqPmSearch(this),null,search_method);

		}

		else {

			if(search_method == 1) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);

				},100);

			}else if(search_method == 2 && dynamic_criterion) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);

				},100);

			}

		}

	});

	$jqPmSearch('#PM_ASForm_'+id_search+' .PM_ASCriterionGroupSelect').unbind('change.eventInstantSearch').bind('change.eventInstantSearch',function() {

		if(step_search) {

			nextStep(id_search,$jqPmSearch(this),null,search_method);

		}

		else {

			if(search_method == 1) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);

				},100);

			}else if(search_method == 2 && dynamic_criterion) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);

				},100);

			}

		}

	});

	$jqPmSearch('#PM_ASForm_'+id_search+' .PM_ASCriterionCheckbox').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {

		if(step_search) {

			nextStep(id_search,$jqPmSearch(this),null,search_method);

		}

		else {

			//Instant search

			if(search_method == 1) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);

				},100);

			}else if(search_method == 2 && dynamic_criterion) {

				setTimeout( function() {

					$jqPmSearch('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);

				},100);

			}

		}

	});

	//Submit search

	if(search_method == 2) {

		$jqPmSearch('#PM_ASForm_'+id_search).ajaxForm(ASFormOptions);

	}

	initNotMulticriteriaElements();

	initToogleBloc();

	initFormSearchBlocLink(id_search);

}

function initSearch(id_search,search_method,step_search,dynamic_criterion)  {

	if($jqPmSearch('#PM_ASearchResultsInner .pagination a').length) {

		$jqPmSearch('#PM_ASearchResultsInner .pagination a').unbind('click.eventSearchLink').bind('click.eventSearchLink',function() {

			setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');

			var destUrl = getAsAjaxUrl($jqPmSearch(this).attr('href'));

			var asExtraParamsReg = new RegExp("&p=[0-9]+|&orderby=[a-z]+|&orderway=[a-z]+|&n=[0-9]+","g");

			var nextExtraParams = destUrl.match(asExtraParamsReg);

			if (nextExtraParams) {

				setTimeout( function() {

					changeHash(id_search,nextExtraParams.join('').substring(1));

				},500);

			}

			$.ajax({

			  url: destUrl,

			  cache: false,

			  data: ($jqPmSearch('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1'),

		      mode		:  'abort',

		      dataType  : 'json',

		  	  port		:	'asSearch',

			  success: function(responseText){

				var htmlResults = responseText.html_products;

				setResultsContents(id_search,htmlResults);

			  }

			});

			return false;

		});

	}

	if($jqPmSearch('#PM_ASearchResultsInner form#productsSortForm select').length) {

		if(ASPSVersion >= '1.4.3') { $(document).ready(function() { $('#selectPrductSort,#selectProductSort').unbind('change');});}

		$jqPmSearch('#PM_ASearchResultsInner form#productsSortForm select').removeAttr('onchange').unbind('change.eventSearchLink').bind('change.eventSearchLink',function() {

			setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');

			if(ASPSVersion < "1.4.3")

				var destUrl = getAsAjaxUrl($jqPmSearch(this).val());

			else {

				var destBaseUrl = getAsAjaxUrl($jqPmSearch('#PM_ASearchResultsInner form#productsSortForm').attr('action'));

				var splitData = $(this).val().split(':');

				var destUrl = destBaseUrl + ((destBaseUrl.indexOf('?') < 0) ? '?' : '&') + 'orderby=' + splitData[0] + '&orderway=' + splitData[1];

			}

			var asExtraParamsReg = new RegExp("&orderby=[a-z]+|&orderway=[a-z]+|&n=[0-9]+","g");

			var nextExtraParams = destUrl.match(asExtraParamsReg);

			if (nextExtraParams) {

				setTimeout( function() {

					changeHash(id_search,nextExtraParams.join('').substring(1));

				},500);

			}

			$.ajax({

			  url: destUrl,

			  cache: false,

			  data: ($jqPmSearch('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1'),

		      mode		:  'abort',

		      dataType : 'json',

		  	  port		:	'asSearch',

			  success: function(responseText){

				var htmlResults = responseText.html_products;

				setResultsContents(id_search,htmlResults);

			  }

			});

			return false;

		});

	}

	if($jqPmSearch('#PM_ASearchResultsInner form.pagination').length) {

		$jqPmSearch('#PM_ASearchResultsInner form.pagination').bind('submit.eventSearchLink',function() {

			setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');

			var curN = $jqPmSearch(this).find('#nb_item').val();

			var asExtraParamsReg = new RegExp("&orderby=[a-z]+|&orderway=[a-z]+","g");

			var nextExtraParams = $jqPmSearch('#nb_item').parents('form').serialize().match(asExtraParamsReg);

			setTimeout( function() {

				if (nextExtraParams) {

					changeHash(id_search,'n='+curN+nextExtraParams.join(''));

				}else changeHash(id_search,'n='+curN);

			},500);

			$.ajax({

			  url: ASPath+'advancedsearch4.php',

			  cache: false,

			  data: ($jqPmSearch('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1&n='+curN),

		      mode		:  'abort',

		      dataType : 'json',

		  	  port		:	'asSearch',

			  success: function(responseText){

				var htmlResults = responseText.html_products;

				setResultsContents(id_search,htmlResults);

			  }

			});

			return false;

		});

	}



	//Override button add to cart from results

	if($jqPmSearch('#PM_ASearchResultsInner').length) {

		if(typeof initAp4CartLink == 'function') {

			initAp4CartLink();

		}

		if(typeof(ajaxCart) != 'undefined') {

			ajaxCart.overrideButtonsInThePage();

		}

		else if(typeof(modalAjaxCart) != 'undefined') {

			modalAjaxCart.overrideButtonsInThePage();

		}

	}

	initFormSearchLink();

}

function changeHash(id_search,addParam)  {

    var newAnchorUrl = decodeURIComponent($jqPmSearch('#PM_ASForm_'+id_search).serialize());

    if(typeof(addParam) != 'undefined') {

    	newAnchorUrl = newAnchorUrl+'&'+addParam;

    }

    newAnchorUrl = '#'+encodeAsParams(newAnchorUrl);

    hashChangeBusy = true;

    $jqPmSearch.bbq.pushState( newAnchorUrl );

    setTimeout( function() {

    	hashChangeBusy = false;

	},1000);

}

function asLaunchHash(curentHash)  {

	var regIdSearch = new RegExp("sid:[0-9]+", "g");

	var id_search = curentHash.match(regIdSearch);

	var regIdSearch2 = new RegExp("sid:", "g");

	if(id_search) {

		id_search = id_search[0].replace(regIdSearch2,'');

		curentHash = decodeAsParams(curentHash);

		setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');

		setlayer('body', '#PM_ASBlockOutput_'+id_search,'PM_ASearchLayerBlock','PM_ASearchLayerBlock');

		$.ajax({

		  url: ASPath+'advancedsearch4.php',

		  cache: false,

		  data: curentHash+'&ajaxMode=1',

	      mode		:  'abort',

	      dataType  : 'json',

	  	  port		:	'asSearch',

		  success: function(responseText){

			var htmlResults = responseText.html_products;

			setResultsContents(id_search,htmlResults);

			  var htmlBlock = responseText.html_block;

			  var htmlBlockSelection =  responseText.html_selection_block;

			  if(htmlBlockSelection) {

				  $jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASSelectionsBlock').html(htmlBlockSelection);



			  }

			  $jqPmSearch('#PM_ASBlockOutput_'+id_search).html(htmlBlock);

			  removelayer('PM_ASearchLayerBlock');

		  }

		});

	}else { location.href = location.href;return;}

}

function asInitAsHashChange()  {

	$jqPmSearch(window).hashchange(function() {

		if(hashChangeBusy) return;

		var curentHash = document.location.hash;

		asLaunchHash(curentHash);

	});

	$jqPmSearch.observeHashChange({interval: 1000});

	$(function() {

		var currentUrl = document.location.toString();

		if (currentUrl.match('#')) {

		  var curentHash = currentUrl.split('#')[1];

		  asLaunchHash(curentHash);

		}

	});

}
