var ajaxScrollerSelectBegin = 0;

jQuery(document).ready(function(){
	// click on next/prev link
	jQuery(".ajaxscroller_prev").click(function(){
		getItemAndPlace(this, "prev");
	});
	jQuery(".ajaxscroller_next").click(function(){
		getItemAndPlace(this, "next");
	});
	
	// scroll automatic every x seconds
	if (ajaxScrollerAutoScroll > 0) {
		autoScroll();
	}
	
	if (ajaxScrollerStopAtLastElement > 0) {
		jQuery(".ajaxscroller_prev").hide();
	}
});
/**
 * Dmitry Bannykh path it
 * Add Func detect URL params, and call it
 */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
/**
 * Basic function for AJAX request
 *
 * @param object cObj: clicked element (prev or next link)
 * @param string nextOrPrev: Link clicked ("next" or "prev")
 */
function getItemAndPlace(cObj, nextOrPrev) {
	// if lang is use
	var lang = gup( 'L' );
	if (ajaxScrollerStopAtLastElement > 0) {
		jQuery(".ajaxscroller_prev, .ajaxscroller_next").fadeOut();
	}

	// stop timeout
	if (ajaxScrollerAutoScroll > 0) {
		window.clearTimeout(autoScroller);
	}
	
	// calculate next record
	if (nextOrPrev == "prev") {
		ajaxScrollerSelectBegin = ajaxScrollerSelectBegin - ajaxScrollerMax;
	} else {
		ajaxScrollerSelectBegin = ajaxScrollerSelectBegin + ajaxScrollerMax;
	}
	if (ajaxScrollerSelectBegin >= ajaxScrollerMaxRowCount) {
		ajaxScrollerSelectBegin = 0;
	}
	if (ajaxScrollerSelectBegin < 0) {
		ajaxScrollerSelectBegin = ajaxScrollerMaxRowCount - ajaxScrollerMax;
	}
	// hook for effects
	hookGetItemAndPlaceStart(cObj, nextOrPrev);
    // Detect URL and add url param "L="
				if (lang>0) {
				urls="index.php&L=".lang;
				} else {
				urls="index.php";	
				}

	// AJAX request
	jQuery.ajax({

		url: urls,
		data: ({id : ajaxScrollerPid, type : ajaxScrollerTypeNum, begin : ajaxScrollerSelectBegin, no_cache : 1}),
		dataType: "json",
		success: function(ret){
			// place new content
			jQuery(cObj).closest(".tx-conajaxscroller-pi1").find(".ajaxscroller_content").html(ret.content);
			
			// scroll automatic every x seconds
			if (ajaxScrollerAutoScroll > 0) {
				autoScroll();
			}
			
			// hide / show next and prev buttons
			if (ajaxScrollerStopAtLastElement > 0) {
				if (ajaxScrollerSelectBegin > 0) {
					jQuery(".ajaxscroller_prev").fadeIn();
				} else {
					jQuery(".ajaxscroller_prev").fadeOut();
				}
				if (ajaxScrollerSelectBegin >= ajaxScrollerMaxRowCount - 1) {
					jQuery(".ajaxscroller_next").fadeOut();
				} else {
					jQuery(".ajaxscroller_next").fadeIn();
				}
			}
			
			// hook for effects
			hookGetItemAndPlaceSuccess(cObj, nextOrPrev);
		}
	});
}

/**
 * Timeout for next automatic scrolling
 */
function autoScroll() {
	autoScroller = window.setTimeout('getItemAndPlace(jQuery(".ajaxscroller_next"))', ajaxScrollerAutoScroll * 1000)
}
