var sliders = {};
var previews = {};
var previewBlocksTimerInt;
var firstPreview = null;
//window.localStorage.clear();

$(document).ready(function() {
				
	var id = $(this).parent().parent().find('.slider').attr('id');
	$('.collections').find('.slider').each(function(index) {
		sliders[this.id] = new CollectionSlider();
	});
	
	$('#bigView').find('.closer').click(function() {
		$('#vual').fadeOut();
		$('#bigView').fadeOut();
		
		if( !browserIsNotIELower9() ) {
			$('.collections').find('.name').find('div.blur').hide();
			$('.collections').find('.name').find('canvas').show();
		}
		else {
			$('.collections').find('.name').find('div.blur').fadeOut();
			$('.collections').find('.name').find('canvas').fadeIn();
		}
	});
	
	$('a#choose').click(function() {
		setCurrentTimeAudio();
		$('#collectionId')[0].submit();
		return false;
	});
	
	var timer = 0;
	var canvas = null;
	var Angle = -Math.PI/2;
	$('.collections').find('.name').find('canvas').each(function(index) {
		if( index == 0 ) {
			firstPreview = $(this).attr('id');
		}
		previews[$(this).attr('id')] = new homePreviewBlocks();
		previews[$(this).attr('id')].mount($(this).attr('id'), Angle);
		Angle -= Math.PI/2;
	});	
	
	if(support_storage('')) {
		var videoIsShown = window.localStorage.getItem('videoIsShown');
	} else {
		var videoIsShown = null;
	}	
	
	if( supports_video() && empty(videoIsShown) && !browserIsMacSafari() && $('#movie').length > 0 ) {	
		var videoBlock = $('#movie')[0];
		
		videoBlock.addEventListener('loadedmetadata', function() {
			if( !isiPad ) {
				$('#videoContainer').find('.centered').css({'margin-top': -videoBlock.videoHeight/2, 'margin-left': -videoBlock.videoWidth/2});
			}
		}, false);
		
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		
		if( !isiPad ) {
			$('#sources').find('.source').each(function() {
				if( screen.width == 1920 ) {
					if( $(this).text().indexOf('_720') != -1 ) {
						var source = document.createElement('source');
						source.src = $(this).text();
						if( $(this).text().indexOf('.ogv') != -1 ) {
							source.type = "video/ogg";
						} else {
							source.type = "video/mp4";
						}
						$(videoBlock).append(source);
					}
				} else {
					if( $(this).text().indexOf('_1920') != -1 ) {
						var source = document.createElement('source');
						source.src = $(this).text();
						if( $(this).text().indexOf('.ogv') != -1 ) {
							source.type = "video/ogg";
						} else {
							source.type = "video/mp4";
						}
						$(videoBlock).append(source);
					}
				}
			});
		} else {
			$('#videoContainer').find('.centered').css({'margin-top': -720/2, 'margin-left': -1024/2});
		}		
		videoBlock.load();
		
		videoBlock.play();
		
		videoBlock.addEventListener('loadeddata', function(){
			$('#videoContainer').find('.loader').fadeOut();
			$('#movie')[0].play();
			$('#videoContainer').find('.centered').fadeIn();
		}, false);
		
		videoBlock.addEventListener('ended', function(){
			$('#videoContainer').fadeOut(function() {
				if( !browserIsNotIELower9() ) {
					setTimeout( function(){
						for( var i in previews ) {
							previews[i].action();
						}
					}, 400);
				} else {
					for( var i in previews ) {
						previews[i].action();
					}
				}
				
				previewBlocksTimerInt = setInterval(previewBlocksTimer, 100);
			});
		}, false);
	} else {
		$('#videoContainer').hide();
		if( !browserIsNotIELower9() ) {
			setTimeout( function(){
				for( var i in previews ) {
					previews[i].action();
				}
			}, 400);
		} else {
			for( var i in previews ) {
				previews[i].action();
			}
		}
		previewBlocksTimerInt = setInterval(previewBlocksTimer, 100);
	}
});

function supports_video() {
	if( !support_playType() ) {
		return false;
	}
	if(canPlayVorbis()) {
		return true;
	}
	if(canPlayMP4()) {
		return true;
	}
	if(canPlayWebM()) {
		return true;
	}
	return false;
}

function support_playType() {
	return !!document.createElement('video').canPlayType;
}

function canPlayVorbis() {
    var v = document.createElement('video');
    return !!(v.canPlayType && v.canPlayType('video/ogg; codecs="theora, vorbis"').replace(/no/, ''));
}

function canPlayMP4() {
    var v = document.createElement('video');
    return !!(v.canPlayType && v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, ''));
}

function canPlayWebM() {
    var v = document.createElement('video');
    return !!(v.canPlayType && v.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/no/, ''));
}

function browserIsMacSafari() {
	var nav = navigator.userAgent.toLowerCase();
	if( nav.indexOf('safari') == -1 ) {
		return false;
	}
	if( nav.indexOf('mac') == -1 ) {
		return false;
	}
	if( navigator.userAgent.match(/iPad/i) != null ) {
		return false;
	}
	return true;
}

/*Bind 'click' event to canvas after preview effect*/
function previewBlocksTimer() {
	if( previews[firstPreview].isFinished() ) {
		clearInterval(previewBlocksTimerInt);
		if( support_storage('') ) {
			window.localStorage.setItem('videoIsShown', '1');
		}
		$('.collections').find('.name').find('canvas').click(function( event ) {
			event.stopPropagation();
			var id = $(this).parent().parent().find('.slider').attr('id');
			
			if( typeof sliders[id] == 'undefined' ) {
				return;
			}
			
			var slider = sliders[id];
			$('.collections').find('.slider').each(function() {
				$(this).height('0px');
			});
			if( !slider.isAlreadySet() ) {
				slider.mount(id, null, 
					{
					butUpActs: {'changeCollectionSmall': slider},
					butDownActs: {'changeCollectionSmall': slider},
					slideActs: {'openDetailBlock': id, 'showSlider': id},
					selectMethod: {
						'selectMethod': 'selectMethodHome',
						'firstSelectMethod': 'drawFirstElements',
						'params': {}}
					},
					'fade',
					{'changeCollectionSmall': slider}
				);
			}
			else {
				slider.restart(false);
				changeCollectionSmall(slider);
			}
		});
	}
}

/*open block with detailed information about collection*/
function openDetailBlock( /*sliderObj*/ id ) {
	$('.collections').find('.slider').fadeOut();
	$('#bigView').find('#PnRt').find('.description').find('.text-block').hide();
	$('#'+id+'_Desc').show();
	$('#bigView').fadeIn();
	$('#vual').fadeIn();
	
	$('#bigView').find('#PnRt').find('.description').find('.vual').height($('#'+id+'_Desc').height()+46);
	
	if( !browserIsNotIELower9() ) {
		$('.collections').find('.name').find('div.blur').show();
		$('.collections').find('.name').find('canvas').hide();
	}
	else {
		$('.collections').find('.name').find('div.blur').fadeIn();
		$('.collections').find('.name').find('canvas').fadeOut();
	}
}

/*mount new sliders to detailed block*/
function showSlider( id ) {
	var slider;
	
	for( var i in sliders ) {
		$('#'+i).height('0px');
	}
	
	var name = id.substr(id.indexOf('_')+1);
	
	if( sliders['Detail_'+name].ID == null ) {
		slider = new CollectionSlider();
		slider.mount( 'Detail_'+name, 1,
			{
				butUpActs: {'changeCollection': slider},
				butDownActs: {'changeCollection': slider},
				slideActs: {},
				selectMethod: {
					'selectMethod': 'selectMethodHomeDetailed',
					'firstSelectMethod': 'drawFirstElementsDetailed',
					'params': {}
				}
			},
			'fade',
			 {'changeCollection': slider},
			parseInt( $('input[name="selectedItem"]').val())
		);
		sliders['Detail_'+name] = slider;
	}
	else {
		slider = sliders['Detail_'+name];
		slider.restart(true);
	}
	
	var sideViewBut = $('#bigView').find('#PnRt').find('#sideView');
	sideViewBut.unbind('click');
	sideViewBut.removeClass('lf-changer-disabled');
	var frontViewBut = $('#bigView').find('#PnRt').find('#frontView');
	frontViewBut.unbind('click');
	frontViewBut.addClass('rt-changer-disabled');
	
	sideViewBut.click(function() {
		if( !slider.isDisabled && !$(this).hasClass('lf-changer-disabled') ) {
			slider.getRightItem();
			$(this).addClass('lf-changer-disabled');
			frontViewBut.removeClass('rt-changer-disabled');
		}
	});	
	
	frontViewBut.click(function() {
		if( !slider.isDisabled && !$(this).hasClass('rt-changer-disabled') ) {
			slider.getLeftItem();
			$(this).addClass('rt-changer-disabled');
			sideViewBut.removeClass('lf-changer-disabled');
		}
	});
}

function drawFirstElements( params, slider) {	
	$.ajax({
		url: 'ajax_request/getSerieImages/'+slider.ID+'/small/0',
		type: "POST",
		async: false,
		success: function(result) {
			result = eval('(' + result+ ')');
			
			for( var i in result ) {
				var img = '<div class="additional-block"><img src="'+slider.dir+'/'+result[i]['SerieImage']['image_front_small']+'"></div>';
				var block = customDrawItem(img, 1, slider.cont, null, slider.slideActs);
				slider.items.push({
					'selector_id': result[i]['SerieImage']['id'],
					'switch': result[i]['SerieImage']['switch_part_id'],
					'frame': result[i]['SerieImage']['shape_id'],
					'block': block
				});
			}
		}
	});
}

/*custom function to select elements from DB*/
function selectMethodHome( params, slider, position, beforeBlock ) {
	var drawingItems = [];
	var selectedItem = slider.items[slider.currIndex]['switch'];
	
	var direction = position > 0 ? 'next' : 'prev';
	
	$.ajax({
		url: 'ajax_request/getSerieNextImage/'+selectedItem+'/small/'+direction,
		type: "POST",
		async: false,
		success: function(result) {
			result = eval('(' + result+ ')');
			var img = '<div class="additional-block"><img src="'+slider.dir+'/'+result['SerieImage']['image_front_small']+'"></div>';
			var block = customDrawItem(img, position, slider.cont, beforeBlock, slider.slideActs);
			
			if( position == -1 ) {
				var TMPItems = new Array();
				//TMPItems.push(obj);
				TMPItems.items.push({
					'selector_id': result['SerieImage']['id'],
					'switch': result['SerieImage']['switch_part_id'],
					'frame': result['SerieImage']['shape_id'],
					'block': block
				});
				for( var i in slider.items )
				TMPItems.push(slider.items[i]);
				slider.items = TMPItems;
			}
			else {
				slider.items.push({
					'selector_id': result['SerieImage']['id'],
					'switch': result['SerieImage']['switch_part_id'],
					'frame': result['SerieImage']['shape_id'],
					'block': block
				});
			}
		}
	});
}

/*custom function to draw slides*/
function customDrawItem( obj, position, cont, beforeBlock, slideActs ) {
	var block = document.createElement('DIV');
	$(block).addClass('collection-item');
	$(block).html(obj);
	cont.find('.overflow').append(block);
	
	if( position == -1 ) {
		$(beforeBlock).before(block);
	}
	var img = $(block).find('img');
	if( !empty(slideActs) ) {
		$(img).click(function() {
			for( var i in slideActs ) {
				window[i](slideActs[i]);
			}
		});
	}
	preLoadImages( $(block).find('img')[0] );
	
	return block;
}

function preLoadImages( obj ) {
	if( obj.width > 100 ) {
		$(obj).css('margin-left', '-'+$(obj).width()/2+'px');
	}
	else {
		setTimeout(function(){preLoadImages(obj)}, 1000);
	}
}

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}

function drawFirstElementsDetailed( params, slider) {	
	$.ajax({
		url: 'ajax_request/getSerieImages/'+slider.ID+'/all/0',
		type: "POST",
		async: false,
		success: function(result) {
			result = eval('(' + result+ ')');
			for( var i in result ) {
				var img = [];
				img.push('<div class="additional-block"><img src="'+slider.dir+'/'+result[i]['SerieImage']['image_front_big']+'"></div>');
				img.push('<div class="additional-block"><img src="'+slider.dir+'/'+result[i]['SerieImage']['image_side_big']+'"></div>');
				var block = customDrawItemDetailed(img, 1, slider.cont, null, slider.slideActs);
				slider.items.push({
					'selector_id': result[i]['SerieImage']['id'],
					'switch': result[i]['SerieImage']['switch_part_id'],
					'frame': result[i]['SerieImage']['shape_id'],
					'block': block
				});
			}
		}
	});
}

/*custom function to select elements from DB*/
function selectMethodHomeDetailed( params, slider, position, beforeBlock ) {
	var selectedItem = slider.items[slider.currIndex]['switch'];
	
	var direction = position > 0 ? 'next' : 'prev';
	
	$.ajax({
		url: 'ajax_request/getSerieNextImage/'+selectedItem+'/small/'+direction,
		type: "POST",
		async: false,
		success: function(result) {
			result = eval('(' + result+ ')');
			var img = [];
			img.push('<div class="additional-block"><img src="'+slider.dir+'/'+result['SerieImage']['image_front_big']+'"></div>');
			img.push('<div class="additional-block"><img src="'+slider.dir+'/'+result['SerieImage']['image_side_big']+'"></div>');
			var block = customDrawItemDetailed(img, position, slider.cont, beforeBlock, slider.slideActs);
			
			if( position == -1 ) {
				var TMPItems = new Array();
				//TMPItems.push(obj);
				TMPItems.items.push({
					'selector_id': result['SerieImage']['id'],
					'switch': result['SerieImage']['switch_part_id'],
					'frame': result['SerieImage']['shape_id'],
					'block': block
				});
				for( var i in slider.items )
				TMPItems.push(slider.items[i]);
				slider.items = TMPItems;
			}
			else {
				slider.items.push({
					'selector_id': result['SerieImage']['id'],
					'switch': result['SerieImage']['switch_part_id'],
					'frame': result['SerieImage']['shape_id'],
					'block': block
				});
			}
		}
	});
}

/*custom function to draw slides*/
function customDrawItemDetailed( objects, position, cont, beforeBlock, slideActs ) {	
	var parentBlock = $(document.createElement('DIV'));
	parentBlock.addClass('row-block');
	cont.find('.overflow').append(parentBlock);
	var index = 1;
	for( var i in objects ) {
		var block = document.createElement('DIV');
		$(block).addClass('collection-item');
		$(block).addClass('list-'+index);
		var itemInd = parseInt(i)+1;
		$(block).addClass('item-'+itemInd);
		$(block).html(objects[i]);
		parentBlock.append(block);
		
		if( objects.length == 1 ) {
			if( position == -1 ) {
				$(beforeBlock).before(block);
			}
		}
	
		if( !empty(slideActs) ) {
			$(block).click(function() {
				for( var i in slideActs ) {
					window[i](slideActs[i]);
				}
			});
		}		
		index++;
	}
	
	cont.find('.overflow').append(parentBlock);
	
	$(parentBlock).find('img').each(function() {
		preLoadImages( this );
	});
	
	return parentBlock;
}

/*change collection settings*/
function changeCollectionSmall( slider ) {
	changeCollection( slider );
	$('input[name="selectedItem"]').val(slider.getCurrentOffset());
}

/*change collection settings*/
function changeCollection( slider ) {
	$('input[name="defCollectionId"]').val(slider.getCurrentCollection());
	$('input[name="frame"]').val(0);//
	$('input[name="switch"]').val(0);//
	$('input[name="selectorId"]').val(slider.getSelectorId());
}
