//google.load('search', '1', {"language" : "uk"});
var $Thesis=new Thesis();
$.effects.transferOrigenale = function(o) {
	return this.queue(function() {
		var elem = $(this),
			target = $(o.options.to),
			endPosition = target.offset(),
			animation = {
				top: endPosition.top,
				left: endPosition.left,
				height: target.innerHeight()//,
				//width: target.innerWidth()
			},
			startPosition = elem.offset(),
			transfer = elem.clone()
				.appendTo(document.body)
				.addClass(o.options.className)
				.css({
					zIndex:2001,
					top: startPosition.top,
					left: startPosition.left,
					height: elem.innerHeight(),
					//width: elem.innerWidth(),
					position: 'absolute'
				})
				.animate(animation, o.duration, o.options.easing, function() {
					transfer.remove();
					(o.callback && o.callback.apply(elem[0], arguments));
					elem.dequeue();
				});
	});
};
$(function(){
	$('#Search').autocomplete("/autocomplete/",{multiple: true,multipleSeparator:' '});
	$('.ui-thesis-navbar').each(function(){
		var $t=$(this);
		$(window)
			.scroll(function(event){
				var $p=$t.parent();
				var p={
					t:$p.offset().top,
					h:$p.height()
				};
				var t={
					h:$t.height(),
					min:10,
					max:p.h-$t.height()-10
				};
				var top=($(window).height()-t.h)/2+$(document).scrollTop()-p.t;
				if(top<t.min)top=t.min;
				if(top>t.max)top=t.max;
				$t.stop(false,false).animate({'top':top},'normal');
			})
			.resize(function(){$(this).scroll();})
			.scroll();
	});
	$('.ui-thesis-overview').each(function(){
		var $this=$(this);
		var clear=function(){
			clearTimeout($this.data('timeout'));
			$this.removeData('timeout');
		};
		var timeout=function(){
			if($this.find('.ui-thesis-overview-content-frame').css('zIndex')==1001){
				$this.find('.ui-thesis-overview-fullcontent-toogle').click();
			}
			clear();
		};
		var set=function(){
			$this.data('timeout',setTimeout(timeout,30000));
		};
		$this.find('.ui-thesis-overview-content-frame').click(function(event){
			if(event.target.tagName.toLowerCase()=='a'&&$(event.target).attr('href')!="#")return;
			var overview=$(this);//.closest('.ui-thesis-overview-content-frame');
			if(overview.css('zIndex')==1001){
				var left=overview.css('position','relative').position().left;
				overview
					.css('position','absolute')
					.animate(
						{'width':'170px','left':left},
						function(){
							$(this)
								.css('zIndex','auto')
								.find('.ui-thesis-overview-fullcontent-toogle')
									.removeClass('ui-icon ui-icon-carat-1-w')
									.addClass('ui-icon ui-icon-carat-1-e');
						}
					);
			}else{
				overview
					.css('zIndex',1001)
					.animate(
						{'width':'100%','left':'0'},
						function(){
							var toggle=$(this)
								.find('.ui-thesis-overview-fullcontent-toogle')
									.removeClass('ui-icon ui-icon-carat-1-e')
									.addClass('ui-icon ui-icon-carat-1-w')
									.effect('pulsate','slow');
								set();
						}
					);
			}
			return false;
		});
		$this.find('.ui-thesis-overview-footer,.ui-thesis-overview-quantity-plus,.ui-thesis-overview-sum,.ui-thesis-overview-cart')
			.click(function(){
				var attr=$this.attr('id').split('-');
				if(attr[0]!='Article')return false;
				$Thesis.Shop.SetArticle(attr[0],attr[1],attr[2],attr[3]);
				var count=$Thesis.Shop.GetCount(attr[0],attr[1]);
				$(this.parentNode).find('.ui-thesis-overview-quantity').text(count);
				$Thesis.Shop.Refresh();
				$this.find('.ui-thesis-overview-image img')
					.effect(
						'transferOrigenale',
						{
							to:".ui-thesis-dialog-buy-button:first"//,
						//	className:'ui-widget-header'
						},
						1000
					);
				clear();
				set();
				return false;
			});
		$this.find('.ui-thesis-overview-quantity-minus')
			.click(function(){
				var attr=$this.attr('id').split('-');
				var count=$Thesis.Shop.GetCount(attr[0],attr[1])-1;
				if(count<=0)$Thesis.Shop.UnSetArticle(attr[0],attr[1]);
				else $Thesis.Shop.SetCount(attr[0],attr[1],count);
				$(this.parentNode).find('.ui-thesis-overview-quantity').text(count);
				$Thesis.Shop.Refresh();
				clear();
				set();
				return false;
			});
	});
	//$Thesis.Shop.SetArticle(class,id,price,weight);
	$("#Counter-Buy").text($Thesis.Shop.GetPropertySum("Count"));
	$("#Price-Buy").text($Thesis.Shop.GetFloat($Thesis.Shop.GetPrice(),2));
	var $FormHelper={
		"Search":"Шукати",
		"Login":"Логін",
		"Password":"Пароль"
	};
	for(var $ID in $FormHelper){
		$("#"+$ID)
			.bind("focus",function(){
				if($(this).val()==$FormHelper[$(this).attr("id")]){
					$(this).val("");
				}
			})
			.bind("blur",function(){
				if($(this).val()==""){
					$(this).val($FormHelper[$(this).attr("id")]);
			}})
			.triggerHandler("blur");	
	}
	$(".jQuery-UI-Tabs").tabs({
		fx: {opacity:'toggle'}
	});
	$(".jQuery-UI-Accordion").accordion({
		autoHeight:false,
		collapsible:true
	});
	$(".jQuery-Plugin-jstree").tree({
		ui:{theme_name:"thesis"},
		callback:{
			onselect:function($Node){
				window.location.href=$("a",$Node).attr("href");
			}
		}
	});
	function jQueryUIEffectBounce(){
		$(this).effect("bounce");
	}
	var $Dialogs={
		"Dialog-Text":{
			title:"Фрагмент тексту",
			height:$(document.body).height(),
			width:$(document.body).innerWidth(),
			buttons:{"Зачинити":function(){$("#Dialog-Text").dialog("close");}},
			open:function(){
				$("#Dialog-Text ul:eq(0)")
				.wrap('<div class="Contents ui-widget"><div class="ui-widget-content"></div></div>')
				.tree({
					ui:{theme_name:"thesis"},
					callback:{
						onselect:function($Node){
							window.location.href=$("a",$Node).attr("href");
						}
					}
				});
				$("#Dialog-Text .Contents>div:eq(0)").before('<div class="ui-widget-header">Зміст</div>');
				var Element=$("#Dialog-Text .Contents:eq(0)");
				Element.addClass("Contents").css('right',Element.offset().left+10);
				Element.draggable({containment:$("#Dialog-Text"),handle:Element.find(".ui-widget-header")});
				$("#Dialog-Text").unbind('dialogopen');
				$("#Dialog-Text").dialog('option', 'open', function(){});
			}
		},
		"Dialog-Illustration":{
			title:"Ілюстрації",
			buttons:{"Зачинити":function(){$("#Dialog-Text").dialog("close");}}
		},
		"Dialog-Review":{
			title:"Рецензії",
			buttons:{"Зачинити":function(){$("#Dialog-Text").dialog("close");}}
		},
		"Dialog-Award":{
			title:"Відзнаки",
			buttons:{"Зачинити":function(){$("#Dialog-Text").dialog("close");}}
		},
		"Dialog-Registration":{
			title:"Реєстрація / Дані користувача",
			height:450,
			width:400,
			buttons:{
				"Запам`ятати":function(){
					$Thesis.Auth.Registration();
				}
			}
		},
		"Dialog-Buy":{
			title:"Кошик",
			open:function(event,ui){
				$Thesis.Shop.Load();
			},
			close:function(){
				window.location.reload();
			}
		}
	};
	for(var $ID in $Dialogs){
		var $ButtonID=$ID.replace("Dialog-","Dialog-Button-");
		var $TheOptions={
			autoOpen: false,
			modal: true,
			height:500,
			width:800,
			resizable: false,
			draggable: false
		};
		for(var $Key in $Dialogs[$ID]){
			$TheOptions[$Key]=$Dialogs[$ID][$Key];
		}
		$("#"+$ID).dialog($TheOptions);
		$("#"+$ButtonID).click(function(){
			$("#"+$(this).attr("id").replace("Dialog-Button-","Dialog-")).dialog("open");
			return false;
		});
	}
	$('.ui-thesis-dialog-buy-button').click(function(){
		$("#Dialog-Buy").dialog("open");
		return false;
	});
	$("#Form-Registration input,#Form-Registration textarea").bind('blur',function(){
		$Thesis.Auth.CheckField($(this).attr("id"));
	});
	
	$(".Load").each(function(){
		$(this).removeClass("Load");
	});
	
	if(typeof GMap != "undefined"){
		var $Div=$(".GMap");
		var $View=$Div.find(">.View");
    	var $List=$Div.find(".List").append('<ul><li class="Clear"></li></ul>').find(">ul");
    	var $Position=$Div.find(".Position");
    	var $Text=$Div.find(">.Text");
    	//Gmap
		var $GMap = new google.maps.Map(
    		$View.get(0),
    		{
      			zoom: GMap.Markers[GMap.Marker].zoom,
      			center: new google.maps.LatLng(GMap.Markers[GMap.Marker].lat,GMap.Markers[GMap.Marker].lng),
      			mapTypeId: google.maps.MapTypeId.HYBRID
    		}
    	);
    	//Position
    	$Position.refrash=function(){
    		$Position.html("Lat: "+$GMap.center.lat()+";<br/>Lng: "+$GMap.center.lng()+";<br/>Zoom: "+$GMap.zoom+";");
    	};
    	$Position.refrash();
    	google.maps.event.addListener($GMap,'zoom_changed',function(){$Position.refrash();});
  		google.maps.event.addListener($GMap,'drag',function(){$Position.refrash();});
  		//Text
  		$Text.html(GMap.Markers[GMap.Marker].context);
  		//List
    	for(var Key in GMap.Markers){
    		var Marker=GMap.Markers[Key];
    		var $Marker=new google.maps.Marker({
    			map: $GMap,
    			title: Marker.title,
    			visible: true,
    			clickable: true,
    			position: new google.maps.LatLng(Marker.lat,Marker.lng)
    		});
    		google.maps.event.addListener($Marker,'click',function(){
    					var title=this.getTitle()
    					var content=title
    					for(var i in GMap.Markers){
    						if(GMap.Markers[i].title==title&&GMap.Markers[i].description){
    							var content=GMap.Markers[i].description
    							break
    						}
    					}
    					(new google.maps.InfoWindow({
    						content:content,
    						position:this.getPosition()
    					})).open(this.getMap(),this);
    		});
    		var $LI=$("<li><a></a></li>")
    		var $A=$LI.find("a")
    		$List.find('>.Clear').before($LI)
    		$A.data("Marker",Marker);
    		$A.attr("href","/gmap/"+GMap.Map+"/"+Marker.id);
    		$A.html(Marker.title);
    		$A.click(function(){
    			var Marker=$(this).data("Marker");
    			$GMap.setCenter(new google.maps.LatLng(Marker.lat,Marker.lng));
    			$GMap.setZoom(Marker.zoom);
    			$Text.html(Marker.context);
    			$Position.refrash();
    			return false;
    		});
    	}
	}
	
	var animationCounter=0;
	function animation(){
		$('.ui-thesis-frame-overtop-animation:first img').attr('src','/Animation/'+(animationCounter%3)+'.gif');
		animationCounter++;
	}
	animation();
	setInterval(animation,10000);
	/*
	// Create a search control
	var searchControl = new google.search.SearchControl();

	// Add in a full set of searchers
	var siteSearch=new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("Видання");
	siteSearch.setSiteRestriction("teza.in.ua/Article");
	searchControl.addSearcher(siteSearch);
	var siteSearch=new google.search.WebSearch();
	siteSearch.setUserDefinedLabel("Автори");
	siteSearch.setSiteRestriction("teza.in.ua/Author");
	searchControl.addSearcher(siteSearch);

	// tell the searcher to draw itself and tell it where to attach
	var DrawOpt=new google.search.DrawOptions();
	DrawOpt.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
	searchControl.draw(document.getElementById("GSearch"),DrawOpt);

	// execute an inital search
	searchControl.execute("Дика енергія");
	*/
});
