/**
 * trim function
 */
function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}


/*
 * getObj(name)
 *
 * sets object and style
 */
function getObj(name)
{
  if (document.getElementById){
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
	this.obj = getObjNN4(document,name);
	this.style = this.obj;
  }
}

/*
getObjNN4(obj, name)

rekurzivni funkce pro hledani objektu jmena name v Netscapu se zanorenymi
vrstvami, divy.
*/
function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

/**
 * shows element. it allows to choose the way elemtns would be displayed
 * block, inline, table, etc.
 * @param string objectName
 * @param string displayStyle
 */
function showElement(objectName, displayStyle)
{
	objToShow = new getObj(objectName);
	objToShow.style.display = displayStyle;
}

/*
 * hides element
 * @param string objectName
 */
function hideIt(objectName)
{
	objToHide = new getObj(objectName);
	objToHide.style.display = 'none';
}

/**
* switch display state of object - ie display:block <-> none
* @param string objectName
* @param string displayStyle
*/
function toggleElementDisplay(objectName, displayStyle)
{
	objToToggle = new getObj(objectName);
	if (objToToggle.style.display != 'none') {
    	hideIt(objectName);
  	} 
	else {
		showElement(objectName, displayStyle);
	}
}

/**
* reset passed form
* @param string formName
* @param object tinyMCE
*/
function resetForm(formName, tinyMCE)
{
	form = new getObj(formName);
	form.obj.reset();
	
	//reset also tinyMCE form
	//ugly but fast solution:)
	for ( i = 0; i< 2; i++){
		tinyMCE.resetForm(0);
		
	};
}

/**
 * fetchUrlNameFromTitle
 *
 * gets values from item title and makes an url out of them
 */

function fetchUrlNameFromTitle(sourceName, destName)
{
	source  = new getObj(sourceName);
	dest    = new getObj(destName);
	urlName = getRidOfBadCharacters(source.obj.value);

	dest.obj.value = urlName.toLowerCase();
}

/**
 * fetchUrlNameFromTitle
 *
 * onKeyUp gets values from item title, makes url out of them and prints it to the detsination
 */
function changeUrlName(sourceName, destName)
{

	source  = new getObj(sourceName);
	dest    = new getObj(destName);

	urlName = getRidOfBadCharacters(source.obj.value);
	
	dest.obj.value = urlName.toLowerCase();
	return;
}

/**
 * fetchEuroFromCZK
 *
 * gets values from item price, rentPrice -> EUR
 */

function fetchEuroFromCZK(sourceName, destName, exchangeRate)
{
	source  = new getObj(sourceName);
	dest    = new getObj(destName);
	priceEUR = eval((source.obj.value/exchangeRate)*100);
	priceEUR = Math.round(priceEUR);
	priceEUR = eval(priceEUR/100);

	dest.obj.value = priceEUR;
}

/**
 * this function gets rid off unwanted characters in string
 */
function getRidOfBadCharacters(string)
{
	var badChars="áäčďéěíĺľňóôőöŕšťúůűüýřžÁÄČĎÉĚÍĹĽŇÓÔŐÖŔŠŤÚŮŰÜÝŘŽ -/.,?+<>:;{}()!'\"\\";
	var goodChars="aacdeeillnoooorstuuuuyrzaacdeeillnoooorstuuuuyrz---";
	var newString="";
	
	string = trim(string);
	for(i=0;i<string.length;i++)
	{ 
		if (badChars.indexOf(string.charAt(i))!=-1) 
		{
		//when replacing bad characters for good one, we have to check if the last
		//replaced character wasn't "-" so that we are not going to have two or more
		// "-" in a row. 
			if((goodChars.charAt(badChars.indexOf(string.charAt(i)))!='-')||(newString.substring(newString.length-1, newString.length)!='-'))
			{
				newString+=goodChars.charAt(badChars.indexOf(string.charAt(i)));
			}
		}
		else newString+=string.charAt(i);
	}
	return newString;
}




/**
 * checks if required fields are not empty
 * all required fields have to be in class named "required"
 * if the field has specified title than show title in alert - title should 
 * be in format Insert your name. Insert your address. Etc.
 */
function validateForm ()
{
	requiredFields = getElementsByClassName("required");
	
	for (var i=0;i<requiredFields.length;i++)
	{
		if ( trim (requiredFields[i].value) == "" ){
			if (requiredFields[i].title){
				alert (requiredFields[i].title);
			}
			else{
				alert ("Je třeba vyplnit všechny povinné položky!");
			}
			requiredFields[i].focus();
			return false;
		}
	}
	return true;
}

/**
* gets all element with specified class name
* @param string clsName 
* @return array all elements with specified class name
*/	
function getElementsByClassName(clsName) 
{ 
	var arr = new Array(); 
	var elems = document.getElementsByTagName("*");
	for ( var cls, i = 0; ( elem = elems[i] ); i++ )
	{
		if ( elem.className.indexOf(clsName) != -1 )
		{
			arr[arr.length] = elem;
		}
	}
	return arr;
}

/**
 * (un)check checkboxes (chk) acording to main checkbox (Check_ctr)
 */
function Check(chk, Check_ctr)
{
	if(Check_ctr.checked==true){
		for (i = 0; i < chk.length; i++)
		chk[i].checked = true ;
	}else{	
		for (i = 0; i < chk.length; i++)
		chk[i].checked = false ;
	}
}


/**
 * hides element that should be hidden (has class='hidden')
 * it can not be done directly with css because some js has problems then..
 */
function hideHiddenElements()
{
	elementsToHide   = getElementsByClassName("hidden");
	var display = 'none';	
		
	for (var i=0;i<elementsToHide.length;i++)
	{
		elementsToHide[i].style.display = 'none';
	}
}

/**
 * setValue
 *
 * sets specified value to selected object
 */
function setValue(destName, value)
{
	source 	         = new getObj(destName);
	source.obj.value = value;
}

/**
 *submit form
 */
function submitForm(formName)
{
	form = new getObj(formName);
	form.obj.submit();
}

function setSubmitAction(formName, actionString)
{
	form = new getObj(formName);
	form.obj.action=actionString;
	form.obj.submit();
}


function changeClass(objectName, newClass)
{

	object = new getObj(objectName);
	object.obj.className = newClass;
}

function setFocus(objectName)
{
	objectToSetFocusTo = new getObj(objectName);
	objectToSetFocusTo.obj.focus();

}

/**
 * opens a popup windows with picture specified in path and with specified dimensions
 */
function openPictureWindow(path,width,height)
{
	var top = screen.availheight/2 - height/2;
	var left = screen.availwidth/2 - width/2;

	if (screen.availheight < height) { top = 0; height=screen.availheight;}
	if (screen.availwidth < width) { left = 0; width = screen.availwidth;}

	window.open(path, "window",'width=' + width + ',height=' + height +',top=' + top +',left='+ left);
}

/**
 * Displays a delete confirmation window
 * @param string lang - which language to use
 */ 
function confirmDelete(lang)
{
	var text = "";
	
	switch (lang)
	{
		case 'cz':
		case 'cs':
		default:
			text="Opravdu chcete tuto položku smazat?";
			break;
		case 'de':
			text = "Wollen Sie .... ?";
			break;
		case 'en':
			text= "Are you sure you want to remove this item?";
	}
			
	confirmation = confirm(text);
	if ( confirmation == true ){
		return true;
	}
	else {
		return false;
	}
}

/**
 * Displays a confirmation window
 * @param string text - text to be displayed
 */ 
function confirmDialog(text)
{
	confirmation = confirm(text);
	if ( confirmation == true ){
		return true;
	}
	else {
		return false;
	}
}

/**
 * checks all element that are in class named elements_to_control. if all
 * fields in this class are filled, then shows all elements with elements_to_show_class
 */
function checkIfDisplayHiddenElements()
{
	elementsToShow    = getElementsByClassName("elements_to_show");
	elementsToControl = getElementsByClassName("elements_to_control");
	var visibility = 'visible';
	
		
	for (var i=0;i<elementsToControl.length;i++)
	{
		if ( trim (elementsToControl[i].value) == "" ){
			visibility = 'hidden';
		}
	}
		
	for (var i=0;i<elementsToShow.length;i++)
	{
		elementsToShow[i].style.visibility= visibility;
	}
}

/**
 * Opens filemanager window that is part of tiny_fce to fetch image name
 * and insert it to specified element
 */
function openFckFileManager(field_name, win)
{
	tinyfck_field = field_name;
	tinyfck = win;
	window.open("../javascripts/filemanager/browser.html?Connector=connectors/php/connector.php", "tinyfck", "modal,width=600,height=400");
}


/**
 * toggleDisplay(objectName)
 *
 * display switcher - if object.style.display is none this function turns it to 
 * calls function showit, and vice versa 
 * 
 *
*/
function toggleDisplay(objectName)
{

	objToToggle = new getObj(objectName);
	if(objToToggle.style.display == 'none') {
    	showIt(objectName);
  	} else {
		if(objToToggle.style.display != 'none') {
			hideIt(objectName);
		} else {
			showIt(objectName);
		}
	}
}

/*
 * showIt(objectName)
 * zobrazi objekt jmena (objectName)
*/
function showIt(objectName)
{

	objToShow = new getObj(objectName);
	objToShow.style.display = 'block';
}

// tato funkce bude prohazovat classy u objektu -
// pokud bude nastavena prvni, zapne druhou a vice versa
// vhodn pro zatrhavani polozek v tabulce
// predpoklada ze u tohoto objektu mohou nastat
// prave jen tyto dva stavy
function toggleClasses(objectName, firstClass, secondClass)
{
	object = new getObj(objectName);
	if (object.obj.className == firstClass)
	{
		object.obj.className = secondClass;
	} else
	{
		object.obj.className = firstClass;
	}

}

//"spravne" reseni externich odkazu v strict xhtml webu
function externalLinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "external") 
     anchor.target = "_blank"; 
 } 
}

//oznaci vsechny checkboxy v danem elementu
function selectCheckboxesInElement ( objectName ) {
	var checks = document.getElementById(objectName).getElementsByTagName('input');
	for ( var i=0; i<checks.length; i++ ) {
		if ( checks[i].type == 'checkbox' ) checks[i].checked = true;
	}	
}

//odznaci vsechny checkboxy v danem elementu
function unselectCheckboxesInElement( objectName ) {
	var checks = document.getElementById(objectName).getElementsByTagName('input');
	for ( var i=0; i<checks.length; i++ ) {
		if ( checks[i].type == 'checkbox' ) checks[i].checked = false;
	}	
}

//invertuje oznaceni vsech checkboxu v danem elementu
function invertCheckboxesInElement ( objectName ) {
	var checks = document.getElementById(objectName).getElementsByTagName('input');
	for ( var i=0; i<checks.length; i++ ) {
		if ( checks[i].type == 'checkbox' ) checks[i].checked = !checks[i].checked;
	}	
}

function productAttributesDisplay( container, checkBoxId ) {
	var checked = 0;
	var checks = document.getElementById(container).getElementsByTagName('input');
	for ( var i=0; i<checks.length; i++ ) {
		if ( checks[i].type == 'checkbox' && checks[i].checked ) checked++;
	}
	
	var checkBox = document.getElementById('attribute_'+checkBoxId+'_cb');
	
	if ( checked > 5 ) {
		checkBox.checked = false;
		return;
	}
	
	if ( checkBox.checked )
		showIt('attribute_'+checkBoxId);
	else
		hideIt('attribute_'+checkBoxId);
}

function hideUnselectedAttributes() {

}

//obnoveni obrazku pro captcha
function new_freecap()
{
	// loads new freeCap image
	if(document.getElementById)
	{
		// extract image name from image source (i.e. cut off ?randomness)
		thesrc = document.getElementById("captcha_image").src;
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		// add ?(random) to prevent browser/isp caching
		document.getElementById("captcha_image").src = thesrc+"?"+Math.round(Math.random()*100000);
	} else {
		alert("Sorry, cannot autoreload freeCap image\nSubmit the form and a new freeCap will be loaded");
	}
}

//validace formulare s dvema policky pro hesla
function validateFormWithDualPassword() {
	valid = validateForm();
	
	if (valid) {
		if ( document.getElementById('password').value == document.getElementById('password2').value ) {
			return true;
		}
		alert("Obě zadaná hesla se musí shodovat!");
	}
	
	return false;
}

//postupe zobrazovani prvku pole
function serialShow ( objects, button ) {
	for ( i=0; i<objects.length-1; i++) {
		var obj = document.getElementById(objects[i]);
		if (obj.style.display == 'none') {
			obj.style.display = 'block';
			return;
		}
	}
	
	document.getElementById(objects[i]).style.display = 'block';
	document.getElementById(button).style.display = 'none';
}

//pro vyber vyrobce ze selectu do dvou inputu (name-text, id-hidden) v adsCategory-form
function selectManufacturer(source, destName, destID)
{
	name    = new getObj(destName);
	id    = new getObj(destID);
	name.obj.value = source.text;
	id.obj.value = source.value;
	return;
}

function getObjectValueByID(source) {
	object = new getObj(source);
	value = object.obj.value;
	return value;
}

function confirmDialog(text)
{
	confirmation = confirm(text);
	if ( confirmation == true ){
		return true;
	}
	else {
		return false;
	}
}