var Engine = {
	
	addLoadEvent : function(func) 
	{ 
		 var oldonload = window.onload; 
		 
		 if (typeof window.onload != 'function')
		{ 
			window.onload = func; 
		} 
		else 
		{ 
			window.onload = function()
			{ 
				oldonload();
				func();
			} 
		 } 
	}, 

	addEvent : function()
	{

	} 
},

Forms = {

	field_names : {},
	elements : {}, 

	initLabels : function(elements)
	{
		
		this.elements = elements; 

		var fields = document.getElementsByTagName('label');
	
		for (var i=0, j=fields.length; i<j; i++)
		{
			var ele = fields[i]; 
			
			// Search for parent form element id
			var parent = ele.parentNode;
			while (parent.tagName != 'FORM')
			{				
				parent = parent.parentNode;
				if (parent.tagName == null)
				{
					break;
				}
			}

			if (typeof ele != 'object' || ! Forms.elements[parent.id])
 			{
				continue; 
			}

			var field = $(ele.htmlFor);
			
			field.start_class = field.className; 
			Forms.field_names[ele.htmlFor] = ele.innerHTML; 
			if (! field.value)
			{
				field.value = ele.innerHTML;
			}
			else 
			{
				field.className = field.name + '_active';
			}	
			
			field.onfocus = function focusOn() 
			{ 
				if (this.value == Forms.field_names[this.name]) 
				{ 				
					this.className = this.name + '_active'; this.value = ''; 
					if(this.name == 'login_password') { this.type = 'password'; }
				} 
			}
			field.onblur = function focusOff() 
			{ 
				if (this.value == '')
				{ 
					if(this.name == 'login_password') { this.type = 'text'; }
					this.value = Forms.field_names[this.name]; this.className = this.start_class;					
				}
			}

		}
	}
	
}, 
Ajax = { 

	createRequest : function()
	{ 
		var request = false;

		try { request = new XMLHttpRequest(); }
		catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (failed)  { request = false; } } }
		
		return request; 
	},

	get : function(page, target, callback)
	{
		var request = this.createRequest();
		var self = this;
		
		request.onreadystatechange = function()
		{
		
			if (request.readyState == 4 && request.status == 200)
			{
				
				if (request.getResponseHeader('X-Internal-Error') == 'true')
				{	
					//Engine.messageSetTitle('Kļūda'); // lang
					//Engine.messageDisplay(request.responseText, false); 
					return; 
				}
			
				if (callback)
				{
					callback(request);
					return; 
				}
				else
				{	
					self.update(request, target);
				}

			}

			if (request.readyState == 4 && request.status == 404)
			{
				//alert('404'); 
			} 
		}

		request.open('GET', page, true);
		request.setRequestHeader('X-Requested-With', 'ajax');
		request.send(null);
	},

	update : function(request, target)
	{
		target = $(target);
		
		if (target)
		{
			target.innerHTML = request.responseText;
		}	
	}, 

	// Apstrādājam JSON datus
	parseJSON : function(data)
	{
		// Moderna native JSON handloshana
		var output; 
		if(typeof JSON != 'undefined')
		{				
			output = JSON.parse(data);
		}
		else
		{
			// vajag esceipot
			output = eval('(' + data + ')');
		}

	return output; 
	}
},

Images = {
	
	active : '',
	list : {}, 

	imageSwap : function(element, active)
	{
		
		if (element.className == 'active')
			return; 
		
		var source = this.list[active]; 
		var target = $('image_medium'); 

		var image_small = $('images_small').childNodes; 
		for (var i=0, j=image_small.length; i<j; i++)
		{
			var ele = image_small[i]; 
			
			if (ele.className == 'active')
			{
				ele.className = ''; 
			}
		}
		
		this.active = active; 
		target.src = source.url;
		element.className = 'active';
	}, 
	
	
	imageZoom : function(e) {
	
	var source = this.list[this.active]; 

	// Noversham attelu dubleshanos, var effektivak? 
	var test = $('image_large');
	if (test && test.style.display == 'block')
	{
		test.style.display = 'none'; 
		if ( test.hasChildNodes() )
		{
			while ( test.childNodes.length >= 1 )
			{
				test.removeChild( test.firstChild );       
			} 
		}
	}

	var ele = this.createLayer('image_large');
	
	ele.onclick = function() 
	{ 
		ele.style.display = 'none';
		while (ele.hasChildNodes())
		{
			ele.removeChild(ele.lastChild);
		}
	}

	var img = new Image();
	img.alt = '';
	img.src = source.url; 

	img.onload = function() {
			
		ele.appendChild(img);
			
		var width = (this.naturalWidth ? this.naturalWidth : this.width)

		if (width > ele.offsetWidth)
		{
			ele.style.width = this.width + 'px';
		}
			
		ele.style.height = (this.naturalHeight ? this.naturalHeight : this.height) + 'px'; 
		
		Images.fixSize(ele);

	 }
	
	// IE FIX 
	img.src = source.url; 

	},  
	
	createLayer : function(id)
	{
		var ele = $(id);

		if (! ele)
		{
			var ele = document.createElement('div');
			ele.id = id;

			document.body.appendChild(ele);
		}
		
		ele.style.display = 'block';
		
		return ele; 
	}, 

	fixSize : function(ele)
	{
		var viewport = this.getViewportSize();
		// IE FIX
		var scrollY = (window.scrollY ? window.scrollY : (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop)); 
		var scrollX = (window.scrollX ? window.scrollX : (document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft)); 
		
		var top = scrollY + (viewport.height - ele.offsetHeight) / 2; 
		ele.style.top = top < 0 ? 0 : top + 'px';
		ele.style.left = scrollX + (viewport.width - ele.offsetWidth) / 2 + 'px';
	}, 

	getViewportSize : function()
	{
		var intH = 0, intW = 0;
    
		if (self.innerHeight) 
		{
			intH = window.innerHeight;
			intW = window.innerWidth;
		} 
		else
		{
			if (document.documentElement && document.documentElement.clientHeight)
			{
				intH = document.documentElement.clientHeight;
				intW = document.documentElement.clientWidth;
			 }
			else 
			{
				if (document.body)
				{
					intH = document.body.clientHeight;
					intW = document.body.clientWidth;
				}
			}
		}

	   return {
			height: parseInt(intH, 10),
			width: parseInt(intW, 10)
		};
	}

},
Data = {

	last_search : '',
	activeSuggestion : '',
	recomendations : '',

	search : function(event)
	{
		// ie fix, event avotam
		var element = event.target ? event.target : event.srcElement; 
		
		if ( ! this.recomendations)
		{
			this.recomendations = $('recomendations'); 
		}

		// atsijājam nevēlamās vērtības
		element.value = element.value.replace(new RegExp('(\/|\"|\'|\)', 'g'), '');
		element.value = element.value.replace('\\','');
		
		if (element.value.length <= 1)
		{
			return false; 
		}
		
		// Ieteikumos uz leju
		if (event.keyCode == 40)
		{
			if (this.recomendations.length == 0)
				return; 
			
			this.recomendations.style.visibility = 'visible'; 

			if ( ! this.activeSuggestion)
			{
				this.setActiveSuggestion(this.recomendations.firstChild, 1); 
				return; 
			}
			
			if (this.activeSuggestion.nextSibling)
			{
				this.setActiveSuggestion(this.activeSuggestion.nextSibling, 1);
				return;
			}
			
			return; 
		}
		
		// Ieteikumos uz augšu
		if (event.keyCode == 38)
		{
			if (this.recomendations.length == 0 || ! this.activeSuggestion)
				return; 

			this.recomendations.style.visibility = 'visible';

			if (this.activeSuggestion.previousSibling)
			{
				this.setActiveSuggestion(this.activeSuggestion.previousSibling, 1);
				return;
			}

			return; 
		}
		
		var search = encodeURIComponent(element.value); 
		
		// izvairamies no diviem vienādiem meklējumiem
		if (Data.last_search == search)
		{
			return false;
		}

		var func = function() 
		{ 
			//$('loading').style.display = 'block';			
			Data.last_search = search;

			Ajax.get(element.parentNode.action + search + '/', '', Data.handleSearchResponse); 

		};

		if ( element.zid ) {
			clearTimeout(element.zid);
		}
		element.zid = setTimeout(func, 500);

	}, 
	
	setActiveSuggestion : function(element, update_input)
	{
		// noņemam veco aktīvo elementu
		if (this.activeSuggestion)
		{
			this.activeSuggestion.className = ''; 
		}

		element.className = 'active'; 
		
		this.activeSuggestion = element;
		
		if (update_input == 1)
		{
			var output = this.filterInput(element.innerHTML); 

			$('search_input').value = output; 
		}
	}, 

	filterInput : function(data)
	{
		// prieksh IE vajag ari uppercase, ir effektivaks variants iespejams?
		var output = data.replace('<span>Ieteikumi</span>','').replace('<SPAN>Ieteikumi</SPAN>','');
		output = output.replace(/<\/?[^>]+(>|$)/g, '');

		return output; 
	}, 

	handleSearchResponse : function(request)
	{		
	
		var data; 
		if (request.getResponseHeader('Content-Type') == 'application/json')
		{
			var data = Ajax.parseJSON(request.responseText); 
		}
		
		var target = $('recomendations'); 
		if (! target)
			return; 
		
		if (! data || data == '')
		{
			target.style.visibility = 'hidden'; 
			return; 
		}

		var output = document.createDocumentFragment();
		for (var id in data)
		{
			var li = document.createElement('li');
			li.onclick = function() { 
				$('search_input').value = Data.filterInput(this.innerHTML); 
				$('search').submit(); 
			}; 
			li.onmouseover = function() {
				Data.setActiveSuggestion(this); 
			}; 
			li.innerHTML = data[id] + (id == 0 ? '<span>Ieteikumi</span>' : ''); 
			output.appendChild(li); 
		}
		
		while ( target.hasChildNodes() ) { target.removeChild( target.firstChild ); }
		target.appendChild(output);
		target.style.visibility = 'visible'; 
		window.onclick = function() {
			target.style.visibility = 'hidden';
		}
		
		

	//	var loading = $('loading');
	//	loading.style.display = 'none';
	//	loading.style.height = target.clientHeight -1 + "px";
	//	loading.style.marginTop = -target.clientHeight + "px";
	}

}; 

function $(id) 
{ 
	if ($.elements[id])
	{
		return $.elements[id]; 
	}
	else 
	{ 
		return $.elements[id] = document.getElementById(id);
	}
}
$.elements = {};

Engine.addLoadEvent(function init()
{
	Forms.initLabels({'search':1});
	var search = $('search_input'); 
	if(search) { search.setAttribute("autocomplete", "off"); }
});