var as_location_name = 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;
}

function setlayer(parent, element,elementId,elementClass) {
	var blockWidth = $jqPmSearch(element).outerWidth();
	var blockHeight = $jqPmSearch(element).outerHeight();
	var blockTop = $jqPmSearch(element).offset().top;
	var blockLeft = $jqPmSearch(element).offset().left;

	$jqPmSearch('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>');

	$jqPmSearch('#'+elementId).css({
		width:blockWidth+'px',
		height:blockHeight+'px',
		top:blockTop+'px',
		left:blockLeft+'px',
		position:'absolute',
		zIndex:'1000'
	});
	$jqPmSearch('#'+elementId).fadeTo('fast',0.8);
}
function removelayer(elementId) {
	if($jqPmSearch('#'+elementId).length) {
		$jqPmSearch('#'+elementId).fadeOut('fast',function() {
			$jqPmSearch(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({
	    
	  }, 500, function() {
	      // Animation complete.
		  //$jqPmSearch('#center_column').html(htmlResults);
		  //$jqPmSearch('#center_column').html(htmlResults).find('.breadcrumb').html(oldBreadCrump);
		  if(ASParams[id_search].keep_category_information) {
			  $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);
	window.scrollTo(0,0);
}
function showAsResponse(responseText, statusText, xhr, $form)  {

	var id_search = $form.find('input[name=id_search]').val();
	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(){
			 $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');
			$jqPmSearch(this).addClass('PM_ASCriterionLinkSelected');
		} else {
			$jqPmSearch(this).next('input').attr('disabled','disabled');
			$jqPmSearch(this).removeClass('PM_ASCriterionLinkSelected');
		}
	});
	$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 = {};
	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseenter(function() {
		if(typeof(criteriaOverTimer[$(this).attr('id')]) != 'undefined' && criteriaOverTimer[$(this).attr('id')]) { clearTimeout(criteriaOverTimer[$(this).attr('id')]);criteriaOverTimer[$(this).attr('id')] = false;}
		$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() {
		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);
	});
}
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 initSearchBlock(id_search,search_method,step_search,dynamic_criterion)  {
	$jqPmSearch('#PM_ASBlock_'+id_search+' .PM_ASResetSearch').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {
		/*setTimeout( function() {
			setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');
			$.ajax({
			  url: location.href,
			  cache: false,
		      mode		:  'abort',
		      dataType : 'text',
		  	  port		:	'asSearch',
			  success: function(text){
				var htmlResults = $jqPmSearch(text).find('#center_column');
				setResultsContents(htmlResults,htmlResults);
			  }
			});
		},100);*/
		location.href = location.href;
	});
	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() {
			var destUrl = getAsAjaxUrl($jqPmSearch(this).attr('href'));
			$.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() {
			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];
			}
			$.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() {
			var curN = $jqPmSearch(this).find('#nb_item').val();
			$.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(ajaxCart) != 'undefined') {
			ajaxCart.overrideButtonsInThePage();
		}
		else if(typeof(modalAjaxCart) != 'undefined') {
			modalAjaxCart.overrideButtonsInThePage();
		}
	}
	initFormSearchLink();

}
