function highlightLoginBox(redirect_url) {
  $('#nick').css('background-color', 'yellow').focus();
  $('#password').css('background-color', 'yellow');
  $('#login_redirect').val(redirect_url);
  return false;
}

function textLimitCounter(textarea, counterID, maxLen) {
	cnt = document.getElementById(counterID);
	if (textarea.value.length > maxLen) {
	   textarea.value = textarea.value.substring(0, maxLen);
	}
	cnt.innerHTML = maxLen - textarea.value.length;
}

function checkText(textAreaId) {
	var el = document.getElementById(textAreaId);
	if (el.value == "") {
	   alert('Napište prosím požadovaný text.');
	   return false;
	} else {
	   return true;
	}
}

/**
 * Ukladani historie AJAX 
 */

function ajaxState(action_url, element_id, formId, loadFunc, errorFunc){
	this.action_url = action_url;
	this.element_id = element_id;
	this.formId = formId;
	this.loadFunc = loadFunc;
	this.errorFunc = errorFunc;
};	

if (typeof(dojo) != 'undefined') {
	dojo.extend(ajaxState, {
		back: function() {
			ajaxHtml(this.action_url, this.element_id, this.formId, this.loadFunc, this.errorFunc, true);
		},
		forward: function(){
			ajaxHtml(this.action_url, this.element_id, this.formId, this.loadFunc, this.errorFunc, true);
		}
	});	
	
	dojo.addOnLoad(function() {
		dojo.back.setInitialState(new ajaxState(window.location, 'main', null, null, null, true));
	});
}


function ajaxHtml(action_url, element_id, formId, loadFunc, errorFunc, skipHistory) {
	if (skipHistory == null || !skipHistory) {
		dojo.back.addToHistory(new ajaxState(action_url, element_id, formId, loadFunc, errorFunc));
    }
	
	newLoadFunc = function(response) {
        dojo.byId(element_id).innerHTML = response;
        
	     if (typeof(loadFunc) == 'function') 
		    loadFunc(response);   				
	}
	
	return ajaxResponse(action_url, formId, newLoadFunc, errorFunc, true);
}

function ajaxAlert(action_url, formId, loadFunc, errorFunc) {
	newLoadFunc = function(response) {
		alert(response);
	    if (typeof(loadFunc) == 'function') 
	    	loadFunc(response);   		
	}
	
	return ajaxResponse(action_url, formId, newLoadFunc, errorFunc, true);
}

function ajaxResponse(action_url, formId, loadFunc , errorFunc, skipHistory) {	
	if (skipHistory == null || !skipHistory) {
		dojo.back.addToHistory(new ajaxState(action_url, formId, loadFunc, errorFunc));
    }
		
	var dojoXhrSettings = {
		url: action_url,
		handleAs: "text",
		load: function (response) {           
		   if (typeof(loadFunc) == 'function') 
			   loadFunc(response);
           
           return false;
		},
        error: function(data){
		   if (typeof(errorFunc) == 'function') 
			   errorFunc(data);			
			
	      return true;
        }, 
        timeout: 6000,
		headers: {"X-Requested-With": "XMLHttpRequest"}				
	};
	
	if (formId != null) {
	   var form = dojo.byId(formId);

       // oprava chyby, ktera vznika vlivem odlisne hlavicky pozadavku (application/x-www-form-urlencoded; charset=UTF-8)
	   // misto standartni hlavicky (application/x-www-form-urlencoded) bez "; charset=UTF-8"				  
       var content = {};
	   for( i = 0; i < form.elements.length; i++ ) {
	      var element = form.elements[i];
			if (element.name == "" || element.name == null)
			   continue;
			
	      if ((element.type!="radio" && element.type!="checkbox")) {
	    	  content[element.name] = element.value;	    	  
	      } else if (element.checked) {
	    	  content[element.name] = element.value;
	      }
	   }
		
       dojoXhrSettings.form = form;
       dojoXhrSettings.content = content;
       dojo.xhrPost(dojoXhrSettings);
	} else {
	   dojo.xhrGet(dojoXhrSettings);
	}

	return false;
}

function ajaxAddToCart(action_url, element_id, formId, loadFunc, errorFunc) {
	var form = document.getElementById(formId);
	var item_id = form.item_id.value;
	if (!item_id || item_id == null) {
		alert('Vyberte nejprve položku ze seznamu.');
		return false;
	}	
	
	var success = function() { 
		if (typeof(loadFunc) == 'function')
			loadFunc();
		
		ajaxShowToaster('xhrCart', 'Košík aktualizován.', 'message', 2000); 
	};
	var error = function() { 
		if (typeof(errorFunc) == 'function')
			errorFunc();		
		
		ajaxShowToaster('xhrCart', 'Košík se nepodařilo aktualizovat.', 'error', 4000); 
	};
	
	ajaxShowToaster('xhrCart', 'Vkládám zboží do košíku.', 'message', 2000);
	
	try {
		pageTracker._trackEvent('Uzivatel', 'Vlozeni zbozi do kosiku');
	} catch(err) {}
	
	return ajaxHtml(action_url, element_id, formId, success, error, true);	
}

function ajaxDropFromCart(action_url, element_id, formId, loadFunc, errorFunc) {
	var ret = confirm('Určitě chcete tuto položku odstranit z košíku?');	
	if (!ret) {
	   ajaxShowToaster('xhrCart', 'Odstranění položky z košíku přerušeno.', 'message', 2000);		
	   return false;
	}		
	
	var success = function() { 
		if (typeof(loadFunc) == 'function')
			loadFunc();
		
		ajaxShowToaster('xhrCart', 'Košík aktualizován.', 'message', 2000); 
	};
	var error = function() { 
		if (typeof(errorFunc) == 'function')
			errorFunc();		
		
		ajaxShowToaster('xhrCart', 'Košík se nepodařilo aktualizovat.', 'error', 4000); 
	};	
	
	ajaxShowToaster('xhrCart', 'Odstraňuji zboží z košíku.', 'message', 2000);

	try {
		pageTracker._trackEvent('Uzivatel', 'Odstraneni zbozi z kosiku');
	} catch(err) {}		
	
	return ajaxHtml(action_url, element_id, formId, success, error, true);			
}

function ajaxShowToaster(name, text, type, duration) {
	if (type == null) type = "error";
	if (duration == null) duration = 0;
	
	dojo.publish(name, [{ message: text, type: type, duration: duration }]);
	return text;
}


function getLocationByElement(base_url, element, use_element_name) {
	if (use_element_name == null)
	   use_element_name = true;
				
   if (element.value == null || element.value == '' || (!use_element_name && parseInt(element.value) > 0))
      return;

   return base_url + (use_element_name ? "/" + element.name : "" ) + "/" + element.value;
}

// prechod na URL adresu pomoci formularoveho prvku (name = parametr, value = hodnota parametru)
function setLocationByElement(base_url, element, use_element_name) {
   var location = getLocationByElement(base_url, element, use_element_name);
   
   if (location != null) 	
      setLocation(location);
}

// prechod na URL adresu pomoci tlacitka / selectu 
function setLocation(url) {
   if (url=="" || url== null) 
	   return;
		
   window.location = url;
}

// ziska pristup k formulari pomoci 'id'
function getForm(id) {
   if (id=="" || id== null) return; 
   return document.getElementById(id);
}


// zobrazi popup okno s obrazkem      
function showImagePopup(src, alt, width, height) {
  if (!src) return true;
  if (!width || !height) {
      var img = new Image();
      img.src = src;
      width  = img.width;
      height = img.height;
  }
  var content = '<a onclick="window.close();" href="#"><img alt="'+ alt +'" src="'+ src +'" '+ (width ? 'width="'+width+'" ' : '') + (height ? 'height="'+height+'" ' : '') +'border="0"></a>';

  return showPopup(content, alt, width, height, 'imagePopup');
}


// upravi velikost okna podle velikosti obrazku
function updatePopupSize() {
  if (document.images[0]) {
     window.resizeTo(document.images[0].width+28, document.images[0].height+62);
     return true;
  }
  return false;
}

// zobrazi popup okno se zadanym HTML obsahem
function showPopup(content, title, width, height, name, setting) {
  if (!name)  name  = 'stdPopup';
  if (!title) title = '';

  width   = width   ? parseInt(width)+16 : 800;
  height  = height  ? parseInt(height) : 600;
  setting = setting ? setting : 'width='+ width +',height='+ height +',left=30,top=20,scrollbars=yes,resizable=yes,status=yes,toolbar=no,menubar=no,location=no';
  content = '<html><head><title>'+ title +'</title><script language="javascript" src="/scripts/common.js"></script></head><body onload="updatePopupSize();" style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">' + content + '</body></html>';
  wndPopup = window.open('', name, setting, true);
  wndPopup.document.open();
  wndPopup.document.write(content);                                                                                                       
  wndPopup.document.close();
  wndPopup.focus();

  return false;
}

/**
 * http://www.boutell.com/newfaq/creating/windowcenter.html
 */
function wopen(url, name, w, h, resizable)
{ 
  resizable = (resizable== null || resizable) ? "yes" : "no";
	
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable='+ resizable);
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
  
  return win;
}
