jQuery(document).ready(function($){
	//$('.openNyroModal').nyroModal();
	if ($.datepicker) {
		$.datepicker.setDefaults({
			showOn: 'button',
			buttonImage: 'css/img/calendar.gif',
			buttonImageOnly: true,
			dateFormat: 'dd/mm/yy',
			zIndex:6000
		});

		$('.alternateInput').each(function(){
			if($(this).parents('li').find(':hidden').val()=='') $(this).html('&nbsp;');
			else $(this).text($(this).parents('li').find(':hidden').val());
		});
		$('input.datepicker').datepicker({
			maxDate: '+100y',
			minDate: '-100y' ,
			yearRange: '-80:+80',
			changeYear: true,
			changeMonth: true,
			onSelect: function(){
				$(this).focus();
				$(this).parents('li').find('.alternateInput').text($(this).val());
				$(this).parents('li').find('label.error').remove();
			}
		}).keydown(function(e){e.preventDefault();});
	 }

	//$("input[class*='number{']").each(function(){
		//alert($(this).attr('class'));
	//});
	$.fn.setVideoImage=function($elem){
		$(this).each(function(){
			var $this=$(this);
			//$this.imgOld=$this.find("img");
			//$elem.prepend($this.imgOld.clone().addClass("previewImage"));
			$this.img=$this.find('img:first');
			$this.parent=$this.img.parent();
			if($this.img.height()>$this.parent.height()) $this.img.css({width:'auto',height:'100%'});
			if($this.img.width()>$this.parent.width()){
				$this.img.css({width:'100%', height:'auto'});
				$this.img.css({paddingTop:Math.round(Number($this.img.parent().height()-$this.img.height())/2+1)+'px'});
			}
			$this.img.hide();
			$this.img.bind('load',function(){
				$this.img.show();
				if($this.img.height()>$this.parent.height()) $this.img.css({width:'auto',height:'100%'});
				if($this.img.width()>$this.parent.width()){
					$this.img.css({width:'100%', height:'auto'});
					$this.img.css({paddingTop:Math.round(Number($this.img.parent().height()-$this.img.height())/2+1)+'px'});
				}
			});
		});
		return $(this);
	}

	jQuery.extend({
		filterNumber:function(){
			$('input.filterNumber').blur(function(){
				var curVal=$(this).val();
				var patt=/\D/g;
				var newVal=curVal.replace(patt,"");
				$(this).val(newVal);
			});
		},
		addAnimation: function(){
			$.fn.extend({
				render:function(){
					$this=this;
					$this.wraper.attr('id',$this.hashId);
					var swfUrl=$this.image.attr('alt');
					var so = new SWFObject(swfUrl, $this.hashId, $this.width, $this.height, "8", "#ffffff");
					so.addParam("allowFullScreen", "false");
					so.addParam("wmode","opaque");
					so.write($this.hashId);
					$this.wraper.removeAttr('id');
					//$this.append('<img src="" alt="'+swfUrl+'" style="display:none;" />');
				}
			});
			$('.animationSet').each(function(){
				var $this=$(this).addClass('animationContainer').removeClass('animationSet');
				$this.hashId='anim_id'+String(Math.random()).substr(2);
				$this.mode=0;
				$this.width=vPlayerDefW;
				$this.height=vPlayerDefH;
				$this.iWidth=vPlayerDefW;
				$this.iHeight=vPlayerDefH;
				$this.image=$this.find('img').addClass('hidden');
				$this.imageUrl='';
				if($this.find('.animSetMode').length)  $this.mode=Number($this.find('.animSetMode').val());
				if($this.find('.animSetWidth').length)  $this.width=$this.find('.animSetWidth').val();
				if($this.find('.animSetHeight').length)  $this.height=$this.find('.animSetHeight').val();
				if($this.find('.animSetAltWidth').length)  $this.iWidth=$this.find('.animSetAltWidth').val();
				if($this.find('.animSetAltHeight').length)  $this.iHeight=$this.find('.animSetAltHeight').val();
				if($this.find('.animSetImage').length)  $this.imageUrl=$this.find('.animSetImage').val();
				if($this.mode){
					$this.image.wrap('<a href="#"></a>');
					$this.modal=$this.image.parent('a');
					if($this.imageUrl==''){
						$this.css({width:$this.iWidth+'px',height:$this.iHeight+'px'});
						$this.modal.css({width:$this.iWidth+'px',height:$this.iHeight+'px'}).addClass('playAnimation').show()
					}else{
						$this.image.attr('src',$this.imageUrl).css({width:$this.iWidth+'px',height:$this.iHeight+'px'}).show();
					}
					
					if(!$('#animationModal'+$this.hashId).length)	$('body').append(
						'<div class="simple_overlay" id="animationModal'+$this.hashId+'">'+
						'</div>'
					);
					$this.wraper=$('<div class="animationWrap"></div>').css({width:$this.width+'px'}).prependTo($('#animationModal'+$this.hashId).css({width:$this.width+'px'}));
					$this.modal.overlay({
						target: '#animationModal'+$this.hashId,
						expose: '#f1f1f1',
						onBeforeLoad: function(){
							$this.render();
						}
					});
				}else{
					$this.css({width:$this.width+'px',height:$this.height+'px'});
					$this.wraper=$('<div class="animationWrap"></div>').prependTo($this);
					if($this.imageUrl==''){
						$this.render();
					}else{
						$this.wraper.append('<a href=""><img src="'+$this.imageUrl+'" style="width:'+$this.width+'px; height:'+$this.height+'px; display:inline;" /></a>');
						$this.wraper.find('a').click(function(event){
							event.preventDefault();
							$this.render();
						});
					}
				}
			});
		},
		addMedia: function(options){
			/*var settings={
				newW:vPlayerDefW,
				newH:vPlayerDefH
			};
			if(options){$.extend(settings, options);}*/
			if ($.fn.media) {
				$.fn.media.defaults.flvPlayer = baseUrl + '/swf/mediaplayer.swf';
				$.fn.media.defaults.mp3Player = baseUrl + '/swf/mediaplayer.swf';
				$(".cms-link-img").each(function(){
					/*height for mp3*/
					var md=this.className.match(/\{.*\}/);
					md=(md&&md.length) ? md[0] : "";
					var mdHash=md.charAt("0")=="{"?eval("("+md+")"):{};
					
					var mediaW=vPlayerDefW, mediaH=vPlayerDefH;

					if($(this).hasClass('mp3')){
						mediaH=35;
					}else{
						if(mdHash.videoW!=0) mediaW=mdHash.videoW;
						if(mdHash.videoW!=0) mediaH=mdHash.videoH;
					}
					var alignClass='';
					if($(this).hasClass('fRight')) alignClass='fRight ';
					if($(this).hasClass('fLeft')) alignClass='fLeft ';

					var d=$('<div class="'+alignClass+'mediaContainer" href="'+this.href+'"><a href="javascript:;" class="mediaLink" style="position:absolute; left:0; top:0;"></a></div>');
					d.addClass(md).width(mediaW+"px").height(mediaH+"px");
					if($(this).find("img").length && ($(this).find("img").attr('src')!='')){
						//d.css("backgroundImage","url('"+$(this).find("img").attr('src')+"')");
						d.prepend($(this).find("img").clone().addClass("previewImage"));
						d.setVideoImage();
						$(this).next('.hiddenImg').remove();
						$(this).after('<img class="hiddenImg" style="display:none;" src="'+$(this).find("img").attr('src')+'" />')
					}else d.css("background","#000");


					//d.width(mediaW+"px").height(mediaH+"px");
					$(this).replaceWith(d);

					if(mdHash.modal){
						var modalId='videoModal_'+String(Math.random()).substr(2);
						$(this).find('div.videoModalBox').remove();
						d.hide().before('<div class="videoModalBox '+md+'" style="width:'+mdHash.inlineW+'px; height:'+mdHash.inlineH+'px; overflow:hidden;"><a href="#" class="openVideoModal mediaLink" style="display:block; width:'+mdHash.inlineW+'px; height:'+mdHash.inlineH+'px;"></a></div>');
						if(d.next('img').length && (d.next('img').attr('src')!='')) d.prev('div').css('background','url("'+d.next('img').attr('src')+'") no-repeat center center');
							else d.prev('div').css('background-image','none');
						
						if(!$('#'+modalId).length)	$('body').append(
							'<div class="simple_overlay" style="width:auto; padding:12px" id="'+modalId+'">'+
								'<div class="videoModalContent"></div>'+
							'</div>'
						);
						var content=d.clone(true).show();
						$('#'+modalId+' .videoModalContent').html(content);
						d.prev('div').find('.openVideoModal').overlay({
							target: '#'+modalId,
							expose: '#f1f1f1',
							closeOnClick: false,
							onLoad: function(){
								var d=$('#'+modalId+' .mediaContainer');
								d.click(function(event){
									event.preventDefault();
									clickEvent($(this));
								});
								if(mdHash.autostart) d.click();
							}
						});
					}
					var clickEvent=function(div){
						//var div=$(this);
						var m=div.metadata();
						var	useCustomControls=false;
						var madiaHref=div.attr('href');
						if(useCustomControls){
							div.after(
								'<ul class="mediaControls" style="width:'+mediaW+'px">'+
									'<li class="mediaPlay"><a href="#">Play</a></li>'+
									'<li class="mediaPause"><a href="#">Pause</a></li>'+
									'<li class="mediaStop"><a href="#">Stop</a></li>'+
									'<li class="mediaScroll"><a href="#"><span><!--Scroll--></span></a></li>'+
								'</ul>'
							);
							$('.mediaControls a').click(function(event){
								event.preventDefault();
								var media=$(this).parents('ul.mediaControls').prev('.mediaContainer').find('embed').get(0);
								if($(this).parent('li').hasClass('mediaPlay')) media.startPlayback();
								if($(this).parent('li').hasClass('mediaPause')) media.pausePlayback();
								if($(this).parent('li').hasClass('mediaStop')) media.stopPlayback();
								if($(this).parent('li').hasClass('mediaScroll')){
									var pers=(event.clientX-$(this).offset().left)/$(this).width();
									$(this).find('span').width(pers*100+'%');
									media.seek(pers);
								}

							});
						}
						var controlH=0;
						if(div.next('.mediaControls').length) controlH=Number(div.next('.mediaControls').height());
						var options={
							width:mediaW,
							height:mediaH-controlH,
							attrs:{style:'width:'+mediaW+';height:'+Number(mediaH-controlH)+';'}
						};

						$.extend(options,div.metadata());
						var $ddd=div.parent()
						div.media(options);
						$ddd.find('.mediaContainer').attr('href',madiaHref).height(mediaH+"px");
						var tmp=$ddd.find('embed').attr('name');
						mp1proxy[tmp]=$ddd.find('embed').attr('name');
					}
					d.click(function(event){
						event.preventDefault();
						clickEvent($(this));
					});
					if(mdHash.autostart && !mdHash.modal) d.click();
				});
			}
		},
		addCarousel: function(options){
			$('.carouselContainer').each(function(){
				var $t=$(this);
				if($t.find('.toDrop').length) return $t;
				var type="linear";
				var align="0";
				var repeat="true";
				var auto="true";
				var space="0";
				var direction="h-l";
				var background;
				var previewImg="true";
				var width=300;
				var height=200;
				
				if($t.find('.carSetWidth').length) width=$t.find('.carSetWidth').val();
				if($t.find('.carSetHeight').length) height=$t.find('.carSetHeight').val();

                var group_id = String(Math.random()).substr(2);
				
				$t.find('.carouselInit').attr('id','carouselContent').width(width+'px').height(height+'px');
				if($t.parent('.carouselWrapper').length) $t.parent('.carouselWrapper').width(width+'px').height(height+'px');
				var images = new Array();
				$t.find('.carouselUl img').each(function(){
					if($(this).attr('src')==$(this).attr('alt')) images.push({url:$(this).attr('src')});
					else images.push({url:$(this).attr('src'),link:$(this).attr('alt')});
				});
				if($t.find('.carSetType').length) type=$t.find('.carSetType').val();
				if($t.find('.carSetAlign').length) align=$t.find('.carSetAlign').val();
				if($t.find('.carSetRepeat').length) repeat=$t.find('.carSetRepeat').val();
				if($t.find('.carSetAuto').length) auto=$t.find('.carSetAuto').val();
				if($t.find('.carSetSpace').length) space=$t.find('.carSetSpace').val();
				if($t.find('.carSetDirection').length) direction=$t.find('.carSetDirection').val();
				if($t.find('.carSetPreview').length) previewImg=$t.find('.carSetPreview').val();
				if($t.find('.carSetBg').length){
					background=$t.find('.carSetBg').val();
					if(String(background).length!=6){
						background="transparent";
						$t.find('.carSetBg').val('');
					}
				}
				switch (type){
					case 'fading':
						var fadingId='fading_id'+String(Math.random()).substr(2);
						$('#carouselContent p').remove();
						$(this).find('.carouselUl').clone('false').height('').removeClass('carouselUl').addClass('fadingCarousel').appendTo($('#carouselContent')).find('.dragHandle').remove();
						var  $fadingCarousel=$('#carouselContent .fadingCarousel');
						$('#carouselContent').css('overflow', 'hidden');
						if(background=="transparent") background="fff";
						$('#carouselContent, #carouselContent li').css('background','#'+background).removeAttr('id');
						$fadingCarousel.find('img').each(function(){
							var $Img=$(this);
							if($Img.attr('alt')!=$Img.attr('src')) $Img.wrap('<a href="'+$Img.attr('alt')+'" target="_blank" style="border:none; margin:0; padding:0;"></a>');
							var h=Number($Img.height());
							//$.fn.proxiDebugger(h+' - '+height)
							if(h<height) $Img.css({'position':'relative','top':Number((height-h)/2)+'px'});
						});
						$fadingCarousel.attr('id',fadingId).find('li.carouselLi:not(:first)').hide();
						var fadeInt=setTimeout('fadeImages("'+fadingId+'")',3000);
						return $(this);
						break;
					case 'linear':
						var so = new SWFObject("/swf/carousel.swf", "group_"+group_id, width+'px', height+'px', "8", background);
						space="5";
						break;
					case 'diagonal':
						var so = new SWFObject("/js/libs/coverflow/test.swf", "group_"+group_id, width+'px', height+'px', "8", background);
						so.addVariable("preview", previewImg);
						break;
					case 'diaporama':
						var so = new SWFObject("/js/libs/coverflow/test.swf", "group_"+group_id, width+'px', height+'px', "8", background);
						so.addVariable("preview", previewImg);
						break;
					default:
						var so = new SWFObject("/js/libs/coverflow/test.swf", "group_"+group_id, width+'px', height+'px', "8", background);
						so.addVariable("type", type);
						so.addVariable("camera","{z:0,y:-200}");
				}
				/*if(type=='linear'){
					var so = new SWFObject("/swf/carousel.swf", "group_"+group_id, "100%", "100%", "8", background);
				}else{
					var so = new SWFObject("/js/libs/coverflow/test.swf", "group_"+group_id, "100%", "100%", "8", background);
					so.addVariable("type", type);
					so.addVariable("camera","{z:0,y:0:y:-200}");
				}*/
				so.addVariable("speed", $(this).find('.carSetSpeed').val());
				so.addVariable("images", escape($.toJSON(images)));
				so.addVariable("align", align);
				so.addVariable("space", space);
				so.addVariable("direction", direction);
				so.addVariable("repeat", repeat);
				so.addVariable("auto", auto);
				so.addVariable("group", "group_"+group_id);
				if (type == 'diaporama') {
					so.addVariable("type", "diaporama");
					so.addVariable("arrow_y", "0.3");
				}
				so.addParam("allowFullScreen", "false");
				if(background=="transparent") so.addParam("wmode","transparent");
					else so.addParam("wmode","opaque");
				so.write("carouselContent");
				$('#carouselContent').removeAttr('id');
				$t.hide();
				$t.fadeIn(300);
			});
		},
		addModal: function($element){
			//alert($(this).html());
			$('.imgWrapper').each(function(){
				if(!$(this).hasClass('openNyroModal') && $(this).attr('href')=='') $(this).unbind('click').click(function(e){ e.preventDefault(); });
				//else $(this).unbind('click');
			});
			if($('.openNyroModal img').length){
				if($element==undefined) $element=$('a.openNyroModal');
				if($element.length==0) $element=$('a.openNyroModal');
				if($('div.cms[id]:has(a.openNyroModal)').length>1){
					var arr=[];
					$('div.cms:has(a.openNyroModal)').each(function(){
						arr.push($(this).attr('id'));
					});
					for(i in arr){
						if(!$('#newGalery_'+arr[i]).length)	$('body').append(
								'<div class="simple_overlay" id="newGalery_'+arr[i]+'">'+
									'<a class="prev">'+translate('Prev')+'</a>'+
									'<a class="next">'+translate('Next')+'</a>'+
									'<div class="info"></div>'+
									'<img class="progress" src="/css/admin/img/loading_overlay.gif" />'+
								'</div>'
						);
						//alert('#'+arr[i]+' a.openNyroModal');
						$('#'+arr[i]+' a.openNyroModal').overlay({
							target: '#newGalery_'+arr[i],
							expose: '#f1f1f1'
						}).gallery({
							speed: 800,
							template: '<span>'+translate('Image ${index} of ${total}')+'</span>'
						});
					}
				}else{
					if(!$('#newGalery').length)	$('body').append(
						'<div class="simple_overlay" id="newGalery">'+
							'<a class="prev">'+translate('Prev')+'</a>'+
							'<a class="next">'+translate('Next')+'</a>'+
							'<div class="info"></div>'+
							'<img class="progress" src="/css/admin/img/loading_overlay.gif" />'+
						'</div>'
					);
					$element.overlay({
						target: '#newGalery',
						expose: '#f1f1f1'
					}).gallery({
						speed: 800,
						template: '<span>'+translate('Image ${index} of ${total}')+'</span>'
					});
				}
			}
		},
		proxiColorPicker: function(){
			$('.proxiColorPicker:not(".hasProxiColorPicker")').each(function(){
				var colors=['ffffff','000000','ff0000','00ff00','0000ff','ffff00','ff00ff','00ffff'];
				var $input=$(this);
				$input.after('<ul class="proxiColors"><li title="transparent" class="transparentColor">X</li></ul>');
				var $picker=$input.next('.proxiColors')
				for(i in colors){
					$picker.append('<li title="'+colors[i]+'" style="background:#'+colors[i]+'"></li>');
				}
				$picker.find('li').hover(
					function(){
						$(this).addClass('hoverColor');
					},
					function(){
						$(this).removeClass('hoverColor');
					}
				).click(function(){
					if($(this).hasClass('transparentColor')) $input.val('');
						else $input.val($(this).attr('title'));
				});
				$input.addClass('hasProxiColorPicker');
			});
		}
	});
	$.addMedia();
	$.addCarousel();
	$.addModal();
	$.addAnimation();
	$.proxiColorPicker();
	$.filterNumber();
});

var vPlayerDefW=300, vPlayerDefH=160,vPlayerCtrlsH=50;

var mp1proxy = {};

function showCarouselItem(items) {
	$( function () {
		if($.evalJSON(items).link!=undefined && $.evalJSON(items).link!=''){
			window.open($.evalJSON(items).link,'_blank');
		}else{
			if(!$('#carouselModal').length)	$('body').append(
				'<div class="simple_overlay" style="width:auto" id="carouselModal">'+
				'<img class="carouselImg" src="" />'+
				'</div>'
			);
			$('#carouselModal .carouselImg').attr('src',$.evalJSON(items).url);
			var img= $('<img src="'+$.evalJSON(items).url+'" />');
			img.overlay({
				target: '#carouselModal',
				expose: '#f1f1f1'
			});
			img.click();
		}
	});
}

function showImage(items){
	$( function () {
		showCarouselItem(items);
	});
}

function carouselClick(n){
	return false;
}

function fadeImages(id){
	var $this=$('#'+id);
	var $cur=$this.find('.carouselLi:visible');
	var $next;
	if($cur.next('.carouselLi').length) $next=$cur.next('.carouselLi');
	else  $next=$this.find('.carouselLi:first');
	$cur.addClass('static');
	$next.fadeIn(1000,function(){
		$cur.hide().removeClass('static');
		var fadeInt=setTimeout('fadeImages("'+id+'")',3000);
	});
}

var playerSkin='/swf/proxi_skin.swf';

