/**
 * 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);
    };
})(jQuery);

var ASFormOptions = {
	beforeSubmit:  showAsRequest,
	success     :   showAsResponse,
	dataType	: 'html',
	mode		:  'abort',
	port		:	'asSearch',
	data		: { ajaxMode:1 }
};
var ASFormDynamicCrtiterionOptions = {
		beforeSubmit:  showAsRequest,
		success     :   showAsResponse,
		dataType	: 'html',
		mode		:  'abort',
		port		:	'asSearch',
		data		: { with_product: 0,ajaxMode:1 }
};
var ASFormOptionsReset = {
		beforeSubmit:  showAsRequest,
		success     :   showAsResponse,
		dataType	: 'html',
		mode		:  'abort',
		port		:	'asSearch',
		data		: { reset:1,ajaxMode:1 }
	};
var ASFormDynamicCrtiterionOptionsReset = {
		beforeSubmit:  showAsRequest,
		success     :   showAsResponse,
		dataType	: 'html',
		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 = $(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 = $(element).outerWidth();
	var blockHeight = $(element).outerHeight();
	var blockTop = $(element).offset().top;
	var blockLeft = $(element).offset().left;

	$('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);
}
function removelayer(elementId) {
	if($('#'+elementId).length) {
		$('#'+elementId).fadeOut('fast',function() {
			$(this).remove();
		});
	}
}
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();
	var evalAtEnd = true;
	if($(responseText).find('#PM_ASBlock_'+id_search).html()) {
		var htmlBlock = $(responseText).find('#PM_ASBlock_'+id_search);
		step_search = false;
	}
	else if(step_search) {
		var next_id_criterion_group = $form.find('input[name=next_id_criterion_group]').val();
		var htmlBlock = $(responseText).find('#PM_ASCriterions_'+id_search+'_'+next_id_criterion_group);
		if(!htmlBlock.html()) {
			var htmlBlock = $(responseText).find('#PM_ASBlock_'+id_search);

		}
	}
	var htmlResults = $(responseText).find('#PM_ASearchResultsInner');
	if(htmlBlock.html()) {
		if(hookName == 'top') {
			 if(!step_search) {
				 $('#PM_ASBlockOutput_'+id_search).html(htmlBlock);
				 removelayer('PM_ASearchLayerBlock');
			  }else {
				  var htmlBlockSelection =  $(responseText).find('.PM_ASSelectionsInner');
				  if(htmlBlockSelection.html()) {
					  $('#PM_ASBlock_'+id_search+' .PM_ASSelectionsBlock').html(htmlBlockSelection);
				  }
				  $('#PM_ASCriterionsOutput_'+id_search+'_'+next_id_criterion_group).html(htmlBlock);
				  removelayer('PM_ASearchLayerBlock');
			  }
		}
		else {
			  // Animation complete.
			  if(!step_search) {
				  $('#PM_ASBlockOutput_'+id_search).html(htmlBlock);
				  removelayer('PM_ASearchLayerBlock');
			  }else {
				  var htmlBlockSelection =  $(responseText).find('.PM_ASSelectionsInner');
				  if(htmlBlockSelection.html()) {
					  $('#PM_ASBlock_'+id_search+' .PM_ASSelectionsBlock').html(htmlBlockSelection);
				  }
				  $('#PM_ASCriterionsOutput_'+id_search+'_'+next_id_criterion_group).html(htmlBlock);
				  removelayer('PM_ASearchLayerBlock');
			  }
		}

	}

	if(htmlResults.html()) {
		setlayer('body', '#center_column','PM_ASearchLayerResult','PM_ASearchLayerResult');
		evalAtEnd = false;
		var htmlResultsHeight = $(htmlResults).actual( 'innerHeight', { clone : true })+20;
		$('#center_column').animate({
		    height: htmlResultsHeight+'px'
		  }, 500, function() {
		    // Animation complete.
			  $('#center_column').html(htmlResults);
			  removelayer('PM_ASearchLayerResult');
			  globalEval(responseText);
		});
	}
	//Eval javascript in result
	if(evalAtEnd)
		globalEval(responseText);
}
function globalEval(text)  {
	$(text).filter('script').each(function(){
	  	$.globalEval($(this).html());
  });
}
function initNotMulticriteriaElements()  {
	$('.PM_ASNotMulticriteria').unbind('mousedown.eventNotMulticriteriaElements').bind('mousedown.eventNotMulticriteriaElements',function() {
		//For checkbox
		if($(this).attr('type') == 'checkbox') {
			if(!$(this).attr('checked')) {
				var curIndex = $(this).parent('li').index();
				$(this).parent('li').parent('ul').find('li:not(:eq('+curIndex+')) > input[type=checkbox]').removeAttr('checked');
			}
		} else {
			if($(this).addClass('PM_ASCriterionLinkSelected')) {
				var curIndex = $(this).parent('li').index();
				$(this).parent('li').parent('ul').find('li:eq('+curIndex+') > input[type=hidden]').attr('disabled','');
				$(this).parent('li').parent('ul').find('li:not(:eq('+curIndex+')) > input[type=hidden]').attr('disabled','disabled');
				$(this).parent('li').parent('ul').find('li > a').removeClass('PM_ASCriterionLinkSelected');
			}
		}
	});
}
function initToogleBloc()  {
	if($('.PM_ASBlockOutputHorizontal').find('.PM_ASCriterionHide').length) {
		$('.PM_ASBlockOutputHorizontal').find('.PM_ASCriterionsGroup').each(function(){
			 $(this).css('height',$(this).height());
			 $(this).find('.PM_ASCriterionsOutput').css('position','absolute');
		});
	}
}
function initFormSearchLink()  {
	$('.PM_ASCriterionLink').unbind('click.eventFormSearchLink').bind('click.eventFormSearchLink',function() {
		if(!$(this).hasClass('PM_ASCriterionLinkSelected')) {
			$(this).next('input').attr('disabled','');
			$(this).addClass('PM_ASCriterionLinkSelected');
		} else {
			$(this).next('input').attr('disabled','disabled');
			$(this).removeClass('PM_ASCriterionLinkSelected');
		}
	});
	$('.PM_ASCriterionHideToogleClick a').click(function() {
		$(this).parents('.PM_ASCriterions').find('.PM_ASCriterionHide').slideToggle('fast');
		$(this).children('.PM_ASHide, .PM_ASShow').toggle();
	});

	$('.PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseenter(function() {
		$(this).addClass('PM_ASCriterionGroupToogleHover');
		$(this).find('.PM_ASCriterionHide').slideToggle('fast');
		$(this).find('.PM_ASCriterionHideToogleHover').hide();
	});
	$('.PM_ASCriterionHideToogleHover').parents('.PM_ASCriterions').mouseleave(function() {
		$(this).find('.PM_ASCriterionHide').slideToggle('fast',function() {
			$(this).parents('.PM_ASCriterions').removeClass('PM_ASCriterionGroupToogleHover');
		});
		$(this).find('.PM_ASCriterionHideToogleHover').show();
	});
	$(function() {
		$('.PM_ASSelections').find('.PM_ASSelectionsRemoveLink').click(function() {
			$(this).next('input').attr('disabled','disabled');
			$(this).parents('form').ajaxSubmit(ASFormOptions);
		});
	});

}
function nextStep(id_search,e,submit,search_method,dynamic_criterion)  {
	var current_next_id_criterion_group_input = $(e).parents('.PM_ASCriterionsGroup').next('.PM_ASCriterionsGroup').find('input:disabled[name=current_id_criterion_group]');
	if($(current_next_id_criterion_group_input).length) {
		$(e).parents('.PM_ASCriterionsGroup').nextAll('.PM_ASCriterionsGroup').children('.PM_ASCriterionsOutput').children('.PM_ASCriterions').children('.PM_ASCriterionsGroupOuter').html('');
		$('#PM_ASForm_'+id_search).find("input[name=next_id_criterion_group]").val($(current_next_id_criterion_group_input).val());
	}
	setTimeout( function() {
		if(search_method == 2) {
			$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);
		}else {
			$('#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");
	//alert(destUrl);
	if (!destUrl.match(asPathReg)) {
		var asQuery = curUrl.substring(curUrl.indexOf("?",0));
		destUrl = ASPath+'advancedsearch4.php'+asQuery;
	}
	return destUrl;
}
function initSearch(id_search,search_method,step_search,dynamic_criterion)  {

	if($('.PM_ASSelectionsBlock .PM_ASSelectionsDropDownShowLink').length) {
		$('.PM_ASSelectionsBlock .PM_ASSelectionsDropDownShowLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {
			$(this).next('.PM_ASSelectionsDropDownMenu').slideToggle('fast');
	    });
	}

	$('#PM_ASForm_'+id_search+' .PM_ASCriterionLink').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {
		if(step_search) {
			nextStep(id_search,$(this),null,search_method);
		}
		else {
			if(search_method == 1) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);
				},100);
			}else if(search_method == 2 && dynamic_criterion) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);
				},100);
			}
		}
	});
	$('#PM_ASForm_'+id_search+' .PM_ASCriterionGroupSelect').unbind('change.eventInstantSearch').bind('change.eventInstantSearch',function() {

		if(step_search) {
			nextStep(id_search,$(this),null,search_method);
		}
		else {
			if(search_method == 1) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);
				},100);
			}else if(search_method == 2 && dynamic_criterion) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);
				},100);
			}
		}
	});
	$('#PM_ASForm_'+id_search+' .PM_ASCriterionCheckbox').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {
		if(step_search) {
			nextStep(id_search,$(this),null,search_method);
		}
		else {
			//Instant search
			if(search_method == 1) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptions);
				},100);
			}else if(search_method == 2 && dynamic_criterion) {
				setTimeout( function() {
					$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptions);
				},100);
			}
		}
	});
	$('#PM_ASBlock_'+id_search+' .PM_ASResetSearch').unbind('click.eventInstantSearch').bind('click.eventInstantSearch',function() {
		if(search_method == 1) {
			setTimeout( function() {
				$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormOptionsReset);
			},100);
		}else if(search_method == 2 && dynamic_criterion) {
			setTimeout( function() {
				$('#PM_ASForm_'+id_search).ajaxSubmit(ASFormDynamicCrtiterionOptionsReset);
			},100);
		}
	});
	if($('#PM_ASearchResultsInner .pagination a').length) {
		$('#PM_ASearchResultsInner .pagination a').unbind('click.eventSearchLink').bind('click.eventSearchLink',function() {
			var destUrl = getAsAjaxUrl($(this).attr('href'));
			$.ajax({
			  url: destUrl,
			  cache: false,
			  data: ($('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1'),
		      mode		:  'abort',
		      dataType : 'text',
		  	  port		:	'asSearch',
			  success: function(text){
				var htmlResults = $(text).find('#PM_ASearchResultsInner');
				var htmlResultsHeight = $(htmlResults).actual( 'innerHeight', { clone : true })+20;
				$('#center_column').animate({
					opacity:0.2,
				    height: htmlResultsHeight+'px'
				  }, 500, function() {
				    // Animation complete.
					  $('#center_column').html(htmlResults).animate({
							opacity:1
					  });
					  globalEval(text);
				});
			  }
			});
			return false;
		});
	}
	if($('#PM_ASearchResultsInner form#productsSortForm select').length) {
		$('#PM_ASearchResultsInner form#productsSortForm select').removeAttr('onchange').unbind('change.eventSearchLink').bind('change.eventSearchLink',function() {
			var destUrl = getAsAjaxUrl($(this).val());
			$.ajax({
			  url: destUrl,
			  cache: false,
			  data: ($('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1'),
		      mode		:  'abort',
		      dataType : 'text',
		  	  port		:	'asSearch',
			  success: function(text){
				var htmlResults = $(text).find('#PM_ASearchResultsInner');
				var htmlResultsHeight = $(htmlResults).actual( 'innerHeight', { clone : true })+20;
				$('#center_column').animate({
					opacity:0.2,
				    height: htmlResultsHeight+'px'
				  }, 500, function() {
				    // Animation complete.
					  $('#center_column').html(htmlResults).animate({
							opacity:1
					  });
					  globalEval(text);
				});
			  }
			});
			return false;
		});
	}
	if($('#PM_ASearchResultsInner form.pagination').length) {
		$('#PM_ASearchResultsInner form.pagination').bind('submit.eventSearchLink',function() {
			var curN = $(this).find('#nb_item').val();
			$.ajax({
			  url: ASPath+'advancedsearch4.php',
			  cache: false,
			  data: ($('#PM_ASForm_'+id_search).serialize()+'&only_products=1&ajaxMode=1&n='+curN),
		      mode		:  'abort',
		      dataType : 'text',
		  	  port		:	'asSearch',
			  success: function(text){
				var htmlResults = $(text).find('#PM_ASearchResultsInner');
				var htmlResultsHeight = $(htmlResults).actual( 'innerHeight', { clone : true })+20;
				$('#center_column').animate({
					opacity:0.2,
				    height: htmlResultsHeight+'px'
				  }, 500, function() {
				    // Animation complete.
					  $('#center_column').html(htmlResults).animate({
							opacity:1
					  });
					  globalEval(text);
				});
			  }
			});
			return false;
		});
	}

	//Override button add to cart from results
	if($('#PM_ASearchResultsInner').length) {
		if(typeof(ajaxCart) != 'undefined') {
			ajaxCart.overrideButtonsInThePage();
		}
		else if(typeof(modalAjaxCart) != 'undefined') {
			modalAjaxCart.overrideButtonsInThePage();
		}
	}

	//Submit search
	if(search_method == 2) {
		$('#PM_ASForm_'+id_search).ajaxForm(ASFormOptions);
	}
	initFormSearchLink();
	initNotMulticriteriaElements();
	initToogleBloc();
}

