/*
 * JSON Slider - Interactive slide show
 * Examples and documentation at: http://
 * Version: 1.0.0 (01/11/2010)
 * Copyright (c) 2010 Lead eCommerce
 * Licensed under the MIT License: http://en.wikipedia.org/wiki/MIT_License
 * Requires: jQuery v1.3+
*/
;(function($) {
	
	$.fn.jsonSlider = function(jsonUrl, jsonUrlCat, options){
		
		var defaults = {
			autoPlay : false,
			stopMouseOverContent : false,
			interval : 5000,
			mouseEnterInterval : 300,
			easeinInterval : 1000,
			boxPerRequest : 4,
			itemPerRequest : 6,
			itemPerLine : 3,
			totalBoxes : 0,
			currentBox : null,
			currentPartId : 0,
			mouseOverContent : false,
			sliderWidth : '100%',
			boxviewerWidth : 'auto',
			place: {},
			css: {}
		};
		
		var options = $.extend( {}, defaults, options );
		
		var place = this.width( options.sliderWidth ).css( options.css );
		
		options.place.box = $("#iss_box",place);
		options.place.img = $("#iss_img",place);
		options.place.title = $("#iss_title",place);
		options.place.content = $("#iss_content",place);
		options.place.boxes = $("#iss_boxes ul",place);
		options.place.navigation = $("#iss_navigation",place);
		options.place.next = $("#iss_next",place);
		options.place.prev = $("#iss_prev",place);
		options.place.pagination = $("#iss_pagination",place);
		options.place.imgplace = $("#iss_imgplace",place)
		options.sliderWidth = options.place.boxes.parent().width();
		options.place.boxviewer = $(".boxviewer").css( { width : options.boxviewerWidth } );
		
		bindMouseOverContentTriger([place,options.place.boxviewer]);
	
		options.place.next.hide();
		options.place.prev.hide();
		options.place.img.hide();
		options.place.box.hide();
		options.place.boxes.parent().hide();

		options.place.next.click(function(){nextButton()});
		options.place.prev.click(function(){prevButton()});

		var currentJson = [];
		var currentPBox = [];
		var switchTimer = null;
		var showBoxTimer = null;
		
		function setDV( v, d )
		{
			return isset(v)? v : d ;
		}
		function isset( varname )
		{
			return ( typeof( varname ) != 'undefined' );
		}

		function removeHTMLTags( s )
		{
			s = s.replace(/&(lt|gt);/g, function (strMatch, p1){return (p1 == "lt")? "<" : ">";});
			s = s.replace(/<br[^>]+\/?>/g, " ");
			return s.replace(/<\/?[^>]+(>|$)/g, "");
		}

		function genMiniBox( localId, data )
		{
			var boxId = (options.currentPartId*options.boxPerRequest)+(localId);
			return $("<a id=\""+boxId+"\" href=\""+data.link+"\" title=\""+removeHTMLTags(data.anons)+"\"><div id='corner'></div><img src=\""+data.avatar+"\" alt=\""+removeHTMLTags(data.anons)+"\" /><span>"+data.anons+"</span></a>").mouseenter(function(){
				
				var _this = $(this);
				showBoxTimer = setInterval(function(){
					if( options.currentBox != _this.attr('id') )
					{
						showBox( _this.attr('id') );
					}
					clearInterval( showBoxTimer );
				}, options.mouseEnterInterval);
				
			}).mouseleave(function(){clearInterval( showBoxTimer )});
		}
		function genMiniBoxes( data )
		{
			var part = $('<li></li>');
			for( var i = 0; i < data.length; i++ )
			{
				genMiniBox( i, data[i] ).appendTo( part );
			}
			return part;
		}
		function placeMiniBoxes( data )
		{
			genMiniBoxes( data ).appendTo( options.place.boxes );
		}

		function loadPart( partId )
		{
			
			partId = setDV( partId, 0 )
			
			stopAutoPlay();

			if( !isset( currentJson[partId] ) )
			{
				options.place.navigation.addClass('onloading');
				options.place.imgplace.css({'backgroundPosition':'center'});
				
				$.ajax({
					url: jsonUrl+"?part="+partId+"&perreq="+options.boxPerRequest,
					type: 'GET',
					dataType: 'json',
					success: function( json ){

						currentJson[partId] = json.data;
						options.totalBoxes = ( isset( json.totalBoxes ) )? json.totalBoxes : options.totalBoxes;
						setCurrentBoxByPartId( partId );
						options.currentPartId = partId;
	
						placeMiniBoxes( json.data );
						showBox( options.currentBox );
	
						setPagination( partId );
						startAutoPlay();
						
					},
					async: false,
					cache: false
				});
				 
			}
			else
			{
				setCurrentBoxByPartId( partId );
				options.currentPartId = partId;
				showBox( options.currentBox );
				setPagination( partId );
				startAutoPlay();
			}
			
		}
		
		function setPagination( partId )
		{
			options.place.pagination.html((options.currentPartId * options.boxPerRequest + 1)+" - "+( options.currentPartId * options.boxPerRequest + currentJson[partId].length )+" of "+options.totalBoxes);
		}

		function setCurrentBoxByPartId( partId )
		{
			var shift = ( options.currentPartId > partId ) ? ( (options.currentPartId - partId) > 1 )?options.boxPerRequest:1 : 0 ;
			options.currentBox = ( partId + ((shift>1)?1:shift) ) * options.boxPerRequest - shift;
		}

		function posobleParts()
		{
			var a = options.totalBoxes / options.boxPerRequest;
			var b = Math.floor( a );
			return ( ( a - b ) > 0 )?++b:b;
		}
		function checkPart( partId )
		{
			if( ( partId >= posobleParts() ) || ( partId < 0 ) )
			{
				return false;
			}
			return true;
		}

		function showBox( boxId )
		{
			boxId = boxId || 0;
			var data = currentJson[ options.currentPartId ][ boxId - options.currentPartId * options.boxPerRequest ];
			
			options.currentBox = boxId;
			var alt = removeHTMLTags(data.title);
			options.place.imgplace.css({'backgroundPosition':'center'});
			options.place.img.hide();
			options.place.img.attr( "src", data.img );
			options.place.img.attr( "alt", alt );
			options.place.img.attr( "title", alt ).load(function(){
				$(this).fadeIn();
				
				if( options.totalBoxes > options.boxPerRequest )
				{
					options.place.next.show();
					options.place.prev.show();
				}
				options.place.box.show();
				options.place.boxes.parent().show();
				options.place.navigation.removeClass('onloading');
				options.place.imgplace.css({'backgroundPosition':'-50px -50px'});
			});

			options.place.img.parent().attr( "href", data.link );
			options.place.title.html( data.title );
			options.place.content.html( data.content );
			options.place.boxes.stop().animate({left:(-1*options.currentPartId*options.sliderWidth)},{"duration":options.easeinInterval},"easein",function(){alert(1)});
			
			loadPBoxes( data.categoryid );
			
			$("a",options.place.boxes).removeClass('selected');
			$("a#"+boxId, options.place.boxes).addClass('selected');
		}

		function autoShowBox()
		{
			if( !options.mouseOverContent && options.autoPlay )
			{
				options.currentBox = ( options.currentBox++ >= options.boxPerRequest * ( options.currentPartId + 1 ) )? options.currentPartId * options.boxPerRequest : options.currentBox;
				showBox( options.currentBox );
			}
		}

		function startAutoPlay()
		{
			if( ( options.interval > 0 ) && options.autoPlay )
			{
				switchTimer = setInterval(function(){autoShowBox()}, options.interval);

				if( options.stopMouseOverContent )
				{
					options.place.box.mouseenter(function(){clearInterval( switchTimer )}).mouseleave(function(){
						clearInterval( switchTimer );
						switchTimer = setInterval(function(){autoShowBox()}, options.interval);
					});
				}
			}
		}
		
		function bindMouseOverContentTriger( obj )
		{
			for( var i = 0; i < obj.length; i++ )
			{
				obj[i].mouseenter(function(){
					options.mouseOverContent = true;
				}).mouseleave(function(){
					options.mouseOverContent = false;
				});
			}
		}

		function stopAutoPlay()
		{
			options.place.box.unbind('mouseenter').unbind('mouseleave');
			clearInterval( switchTimer );
		}
		
		function nextButton()
		{
			var newId = options.currentPartId + 1;
			if( checkPart( newId ) )
			{
				
				loadPart( newId );
			}
			else
			{
				loadPart( 0 );
			}
		}

		function prevButton()
		{
			var newId = options.currentPartId - 1;
			if( checkPart( newId ) )
			{
				loadPart( newId );
			}
		}
		
		function loadPBoxes( categoryId )
		{
			if( !isset( currentPBox[ categoryId ] ) )
			{
				
				$.ajax({
					url: jsonUrlCat+"?categoryid="+categoryId+"&perreq="+options.itemPerRequest,
					type: 'GET',
					dataType: 'text',
					success: function(data){
						eval("var json=" + data);
						currentPBox[ categoryId ] = json.data;
						buildPBox( json.data );
					},
					async: false,
					cache: false
				});

			}
			else
			{
				buildPBox( currentPBox[ categoryId ] );
			}
		}
		function buildPBox( data )
		{
			options.place.boxviewer.html("");
			for(var i = 0, d = options.itemPerLine; i < data.length; i++)
			{
				if(!(i%d))
				{
					placePBox( data[i], "first" );
				}
				else
				{
					placePBox( data[i], "" );
				}
			}
		}
		function placePBox( box, first )
		{
			var box = $("<div class=\"box "+first+"\"><div class=\"img\"><a href=\""+box.link+"\"><img src=\""+box.avatar+"\" alt=\"\" /></a><div></div></div><div class=\"con\"><p class=\"price\"><sub>"+box.discount+"</sub>"+box.price+"</p><p class=\"h\"><a href=\""+box.link+"\">"+box.title+"</a></p><p class=\"descr\">"+box.desc+"</p><p class=\"grad\"></p></div></div>");
			if($.browser.msie){
				var userAgent = $.browser.version;
				var version = userAgent.substring(0,userAgent.indexOf('.'));
				if( version == 7 )
				{
					box.css({'display':'inline'});
				}
			}
			$(".img img",box).load(function(){
				var yPoz = Math.floor(( 146 - $(this).height() ) / 2);
				$(this).css({"margin-top":yPoz}).fadeIn();
			})
			box.appendTo( options.place.boxviewer );
		}
		
		loadPart( options.currentPartId );
	};
})(jQuery);
