/*jQuery.ajaxSetup({
	timeout: 10000
});*/

jQuery.ajaxSync = function(o){
	var fn = jQuery.ajaxSync.fn, data = jQuery.ajaxSync.data, pos = fn.length;
	
	fn[ pos ] = {
		error: o.error,
		success: o.success,
		complete: o.complete,
		done: false
	};

	data[ pos ] = {
		error: [],
		success: [],
		complete: []
	};

	o.error = function(){ data[ pos ].error = arguments; };
	o.success = function(){ data[ pos ].success = arguments; };
	o.complete = function(){
		data[ pos ].complete = arguments;
		fn[ pos ].done = true;
		if ( pos == 0 || !fn[ pos-1 ] )
			for ( var i = pos; i < fn.length && fn[i].done; i++ ) {
				if ( fn[i].error && data[i].error.length != 0 ) fn[i].error.apply( jQuery, data[i].error );
				if ( fn[i].success && data[i].success.length != 0 ){
					fn[i].success.apply( jQuery, data[i].success );
					
					// local link
					if(typeof(urlParams.jump) != "undefined")
						if(urlParams.jump.length > 0 )
						{ 
							jump = jQuery("*[name='"+ urlParams.jump +"']");
							if(jump.length > 0)
								jQuery(document).scrollTop( jump.offset().top);
						}
				}
				if ( fn[i].complete ) fn[i].complete.apply( jQuery, data[i].complete );

				jQuery.ajaxSync.fn[i] = null;
				jQuery.ajaxSync.data[i] = null;
			}
	};

	return jQuery.ajax(o);
};

jQuery.ajaxSync.fn = [];
jQuery.ajaxSync.data = [];




jQuery.fn.addLoader = function()
{
	return this.each(function() 
	{
		if(!this.loading){
			a = jQuery('<div class="eshop-ajaxloader"><span></span></div>')
			.width(jQuery(this).innerWidth())
			.height(jQuery(this).innerHeight())
			.css({'left': '0px', 
				'top': '0px'});
			jQuery(this).prepend(a).addClass('eshop-hasloader');
			a.css({'left': jQuery(this).offset().left - a.offset().left,
				'top':  jQuery(this).offset().top - a.offset().top});				
		}
		/*.hide()
		.fadeIn(300)*/
		//this.loading = true;
	});
}


jQuery.fn.removeLoader = function()
{
	return this.each(function() 
	{
		//if(this.loading)
		//{
			jQuery('.eshop-ajaxloader', this).remove();
			jQuery(this).removeClass('eshop-hasloader');
			this.loading = false;
		//}
	});
}



function getURL(url, async)
{
	r = $.ajax({
		url: url,
		async: async
	});
	if (!async)
		return( r.status >= 200 && r.status < 300 );
}




function urlParams(url, values)
{
	ajax = "";
	urlParams.jump = "";
	if(typeof(values) == "undefined") 
		values = new Array();
	values["v"] = new Date().getTime();	
	
	for (v in values)
	{
		if(ajax != "") ajax += "&";
		ajax += v +"="+values[v];
	}
	
	l = url.lastIndexOf('#')
	if( l >= 0){
		urlParams.jump = url.substr(l+1);
		url = url.substr(0, l);
	}
	
	ajax = url
		+ ((url.lastIndexOf('?') <= 0 )? '?' : ((url.substr(url.length-1, 1) == '&')?  '' :  '&'  ))
		+ ajax;
	
	return ajax;
}

var popup = null;
function closePopup()
{
	popup.hideAndUnload();
}

function extractScripts(o)
{
	scripts = "";
	jQuery(o).filter('script').each(function(){
		scripts += this.innerHTML;
	}).remove();
	jQuery('script', o).each(function(){													
		scripts += this.innerHTML;													
	}).remove();
	
	return scripts;
}



function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function htmlInject(data)
{
	temp = (typeof(defaultNamespace) != 'undefined' && defaultNamespace != false) &&	document.createElementNS ? document.createElementNS(defaultNamespace,"div") : document.createElement("div");
	temp.innerHTML = data;

	updates = getElementsByClass('eshop-update', temp, 'div');
	scripts = "";
	for (var i= 0;i < updates.length ;i++) 
	{					
		
		s = updates[i].getElementsByTagName('script');
		for (var j= 0;j < s.length ;j++) 
		{
			if (s[j].innerHTML != undefined) scripts += s[j].innerHTML;
		}
		document.getElementById(updates[i].id).innerHTML = updates[i].innerHTML;
	}
	eval(scripts);
	temp = 0;
	
	//fix opera redraw bug
	if (window.opera) {
	   document.body.style += "";
	   document.body.style.position = "relative";
	   document.body.style.position = "static";
	}
	
	jQuery(document).trigger('ajaxupdate');
}

function ErrorPopup(text)
{
	popup = new Boxy(jQuery('<div class="eshop-errorbox"><p>Error:'+ text + '</p>'
							+ '<p>Došlo k chybě, stránka bude obnovena ... </p></div>'),
	{
		title: ' ', 
		closeText: '<span class="eshop-closebutton"></span>', 
		hdraggable: false, 
		modal:true, 
		fixed: false,
		unloadOnHide: true,
		closeable: true
	});
	window.setTimeout('location.reload(true)' , 5000);
}


function ajaxCall(url, loader)
{
	jQuery.ajaxSync({
		url: urlParams(url),
		dataType: 'text',
		success: function(data)
		{	
			jQuery(loader).removeLoader();
			htmlInject(data);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			ErrorPopup(XMLHttpRequest.status+' '+XMLHttpRequest.statusText);
			jQuery(loader).removeLoader();
		}
	});							
					
	jQuery(loader).addLoader();
}




function ajaxInject(config, updateQuery, namespace)
{
	if(typeof(ajaxInject.influence) == undefined)
		ajaxInject.scope = jQuery(document).not(".eshop-custom-content");
			
	if( !updateQuery ) updateQuery = "";
	
	if(typeof(config) == 'string')
	{
		jQuery.getJSON(config,function(c)
		{
			ajaxInject(c, updateQuery, namespace);
		});
	}
	else{
	
		var cancel = false; // stops ajax (for now only link)
		
	//jQuery.getJSON(url,function(components){
		jQuery.each(config, function(i,item){
			// Portal part
			if(namespace){
				if(item.loading){
					loadingArray = item.loading.split(",");
					partNum = 0;
					tempLoading = "";
					
					while (partNum < loadingArray.length){
						loadingArray[partNum] = loadingArray[partNum].trim();
						tempLoading += "#" + namespace + loadingArray[partNum] + ",";
						partNum += 1;
					}
	
					item.loading = tempLoading;
				}
				item.query = "#"+namespace+item.query;
			}

			ajaxUpdate = function(data)
			{
				jQuery(item.loading).removeLoader();
				htmlInject(data);		
			}
			
			ajaxError = function(XMLHttpRequest, textStatus, errorThrown)
			{
				ErrorPopup(XMLHttpRequest.status+' '+XMLHttpRequest.statusText);
			}
			
			switch(item.type)
			{
				case "submit":
				
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').not(".noajax").unbind('click')
					.click(function(){if(this.type == "submit" || this.type == "button"  ){ return false;}})
					.click(function()
					{
						
						var params = {};
						params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = (this.type == "checkbox" && !this.checked)? false : this.value; 
																			
						jQuery(this).parents('form').find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], option[@selected], textarea") //input[@type='submit'],
						.filter(":enabled") 
						.each(function() 
						{
							params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
						}); 
						
						jQuery.ajaxSync({
							data: params,
							type: 'POST',
							dataType: 'text',
							url: urlParams( jQuery(this).parents('form').attr('action') , item.data),
							success: ajaxUpdate,
							error: ajaxError
						});
						jQuery(item.loading).addLoader();
						//return false;
					});
				break;
				case "blursubmit":
					
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').unbind('blur')
					.blur(function()
					{
						var params = {};
						params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
							
						jQuery(this).parents('form').find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], option[@selected], textarea") //input[@type='submit'],
						.filter(":enabled") 
						.each(function() 
						{
							params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value; 
						}); 
						
						jQuery.ajaxSync({
							data: params,
							type: 'POST',
							dataType: 'text',
							url: urlParams( jQuery(this).parents('form').attr('action') , item.data),
							success: ajaxUpdate,
							error: ajaxError
						});
						jQuery(item.loading).addLoader();
						//return false;
					});
				break;
				case "combochange":
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').unbind('change')
					.change(function()
					{
						var params = {};
							
						jQuery(this).parents('form').find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], select, textarea") //input[@type='submit'],
						.filter(":enabled") 
						.each(function() 
						{								
							params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;							
						}); 
						jQuery.ajaxSync({
							data: params,
							type: 'POST',
							dataType: 'text',
							url: urlParams( jQuery(this).parents('form').attr('action') , item.data),
							success: ajaxUpdate,
							error: ajaxError
						});
						jQuery(item.loading).addLoader();
						//return false;
					});
				break;
				case "link":
					//alert("Binding link click event for "+jQuery(item.query).length+" instances of "+item.query);
				
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').not(".noajax").unbind('click')
					.click(function(){
						//Links that have target specified are supposed to open in another window, we'll let them
						//do that without interference.						
										if (!this.target){
											return false;
										}
									 })
					.click(function()
					{
						if(!ajaxInject.cancel){
							jQuery.ajaxSync({
								url: urlParams(this.href, item.data),
								dataType: 'text',
								success: ajaxUpdate,
								error: ajaxError
							});							
							jQuery(item.loading).addLoader();
							//return false;
						}
						ajaxInject.cancel = false;
					});
				break;
				
				case "accordeon":
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').unbind('click')
					.click(function(){return false;})
					.click(function()
					{
						//accordeon navigation does not do ajax, regular link is used.
						var href = jQuery("#"+this.id+" a").attr("href");
						if (href){
							document.location = href;
						}
						return false;
					});
				break;
					
				case "popup":
					jQuery(item.query, ajaxInject.scope).filter(updateQuery + ' *').unbind('click')
					.click(function(){return false;})
					.click(function()
					{
						jQuery.ajaxSync({
							url: urlParams(this.href, item.data),
							dataType: 'text',
							success: function(data)
							{
								p = jQuery('div.eshop-popup',data);
								scripts = extractScripts(p);
								popup = new Boxy(p,
								{
									title: ' ', 
									closeText: '<span class="eshop-closebutton"></span>', 
									hdraggable: false, 
									modal:true, 
									fixed: false,
									unloadOnHide: true,
									closeable: (item.closeable)? true : false
								});
								if( popup.getPosition()[1] < 0) popup.moveToY(0);
								
								eval(scripts);
							}
						});
						//return false;
					});				
				break;
				// direct call
				default:
					//alert("Binding link click event for "+jQuery(item.query).length+" instances of "+item.query);
					
					jQuery.ajaxSync({
						url: urlParams(this.href, item.data),
						dataType: 'text',
						success: ajaxUpdate,
						error: ajaxError
					});							
					jQuery(item.loading).addLoader();
					//return false;
			}
		})
	}
}

function ajaxLoadPart(query, url)
{
	jQuery(query).load(url);
}


