// WHISPERER BEGIN 
var ul = '';
var show_count = 1;
var selected_whisper = 0;

function changeHighlight(highlight){
		var lis = ul.getElementsByTagName('LI');
		for (i in lis){
			var li = lis[i];

			if (highlight == i){
				li.className = "selected";
			}else{
				li.className = "";
			}
		}
}
	
function whisper_display(st) {
    if (! ul){
        ul = document.getElementById("suggest");
    }
    whisper_div = document.getElementById("whisper_div");
    
	self.act = st;
	if (st){
		clearTimeout(self.timer);
		ul.style.visibility = "visible";
	}else{
		var f = function(){ul.style.visibility = "hidden";}
		self.timer = setTimeout(f, 500);
	}
}

function testwhisperkey(e){                                         //tohle se nevola a nevim proc
    alert ('testk');
    var KEYUP = 38;
	var KEYDN = 40;
	var ENTER = 13;
    e = fixE(e);
	if (e.which == ENTER) {                                        //odeslat aktualni podle selected_whisper
	}
	if (e.which == KEYDN) {
	   selected_whisper++;
	   changeHighlight(selected_whisper);
	} 
	   
    
}

function whisper_show(searchText, results){
	while (ul.childNodes.length > 0)
		ul.removeChild(ul.childNodes[0]);
    if (searchText == null){
        return (0);
    }
	for (var i=0; i < searchText.length; i++){
		var li = document.createElement("LI");
		if (i==0){
            li.className = "selected";
            var_selected_whisper = 0;
        }
		var label = searchText[i];
		if (show_count == 1){
        	li.innerText = searchText[i] + ', '+ results[i];
        }else{
        	li.innerText = searchText[i];
        }
		ul.appendChild(li);
		li.onclick = function(){
		    var text = this.innerText;
		    var to = text.lastIndexOf(',');
		    if (show_count){
			    document.getElementById("id_whisper").value = text.substring(0,to);
			}else{
			    document.getElementById("id_whisper").value = text;
            }
		}
	}
}


function whisper(whisperElement, homeUrl, action_id, show_count_item){
    if (! canEnterCritical('whisper')){
       return false;
   }
   show_count=show_count_item;
   args = new Array(action_id, whisperElement.value, show_count_item);
   smarty = '';
   callFunction = 'whisper';
   returnFunction = 'whisperCB';
   returnFunctionArgs = whisperElement.id;
   oldurl = url;
   url = homeUrl + '/?ajax=1';
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
   url = oldurl;
}

function whisperCB(result, id, error){
    eval(result);
}
// WHISPERER END







function insertForm(new_url, form_item){
    if (! canEnterCritical('insertForm')){
       return false;
   }
   oldUrl = url;
   url=new_url;
   
   callFunction = 'insertForm';
   args = new Array(form_item,0);
   smarty = '_component/insertform';
   returnFunction = 'insertFormCB';
   returnFunctionArgs = form_item;
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
   url = oldUrl;
}

function insertFormCB(result, id, error){
    var editdummy = document.getElementById('editdummy');
    editdummy.innerHTML = result;
}

function insertAtCursorForm(form_id, formitem){
    myForm = "document.wrform."+formitem;
    insertAtCursor(eval(myForm), '{{form(' + form_id + ')}}');
    document.getElementById('editdummy').innerHTML='';
}

function insertImage(photodisplay_id, form_item){
    if (! canEnterCritical('insertImage')){
       return false;
   }
   callFunction = 'insertImage';
   args = new Array(photodisplay_id,form_item);
   smarty = 'page/ajax/insertimage';
   returnFunction = 'insertImageCB';
   returnFunctionArgs = '';
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
}

function insertImageCB(result, id, error){
    var editdummy = document.getElementById('editdummy');
    editdummy.innerHTML = result;
    
}


function insertYoutube(new_url, form_item){
    
   oldUrl = url;
   url=new_url;
   callFunction = 'youtube';
   args = new Array(form_item,0);
   smarty = '_component/insertyoutube';
   returnFunction = 'insertYoutubeCB';
   returnFunctionArgs = form_item;
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
   url = oldUrl;
}

function insertYoutubeCB(result, id, error){
    var editdummy = document.getElementById('editdummy');
    editdummy.innerHTML = result;
}

function insertYoutubeAtCursor(url, formitem){
    myForm = "document.wrform."+formitem;
    insertAtCursor(eval(myForm), '{{youtube(' + url + ')}}');
    document.getElementById('editdummy').innerHTML='';
}

function showPhotos(gallery_id){
   if (! canEnterCritical('showPhotos')){
       return false;
   }
   document.wrform.photodisplay_id.value = gallery_id;
   callFunction = 'showphotos';
   args = new Array(gallery_id,0);
   smarty = 'page/ajax/show_photos';
   returnFunction = 'showPhotosCB';
   returnFunctionArgs = '';
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
}
    
function showPhotosCB(result, id, error){
    elementId = document.getElementById("page_photos");
    elementId.innerHTML = result;

}


function getRadioValue(radio){
    if (!radio.length){
        if (radio.checked){
            return (radio.value);
        }else{
            return (0);
        }
    }
    for (var i=0; i < radio.length; i++){
        if (radio[i].checked){
            var rad_val = radio[i].value;
        }
    }
    return (rad_val);
}

function insertAtCursorValue(image_id, formitem){
    size = document.wrform.ajax_insertimage.value;
    
    rad_val = getRadioValue(document.wrform.ajax_insertimage);
    position = getRadioValue(document.wrform.ajax_insertalign);
    
    var position_char = '*';
    if (position == 2) position_char = '<';
    if (position == 3) position_char = '>';
    
    text = '[* {{image('+image_id+','+rad_val+')}} '+ position_char +']';
    myForm = "document.wrform."+formitem;
    insertAtCursor(eval(myForm), text,'');
    document.getElementById('editdummy').innerHTML='';
}




function insertAtCursor(myField, myValue1, myValue2, myValueNoSel) {
if (! myValue2) myValue2 = '';
if (! myValueNoSel) myValueNoSel = myValue1;
//alert ("zacatek:"+myField.scrollTop);
visiblePosition = myField.scrollTop;

//IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        if (sel.text){
            sel.text = myValue1+sel.text+myValue2;
        }else{
            sel.text = myValueNoSel;
        }
        myField.focus();
    }
//MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == '0') {
   
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        
        
        if (startPos == endPos){
            myField.value = myField.value.substring(0, startPos) 
                      + myValueNoSel
                      + myField.value.substring(endPos, myField.value.length);
            myField.selectionStart = startPos + myValueNoSel.length;
            myField.selectionEnd = myField.selectionStart;
        }else{
            selLength = myField.selectionEnd - myField.selectionStart;
            myField.value = myField.value.substring(0, startPos)
                      + myValue1 
                      + myField.value.substring(myField.selectionStart, myField.selectionEnd)
                      + myValue2 
                      + myField.value.substring(endPos, myField.value.length);
            myField.selectionStart = startPos + myValue1.length + myValue2.length + selLength;
            myField.selectionEnd = myField.selectionStart;
        }
        myField.focus();
        myField.scrollTop = visiblePosition;
        //alert (myField.scrollTop); 

    } else {
        myField.value += myValue1+myValue2;
    }

}



function insertimage_photos(gallery_id){
   if (! canEnterCritical('showPhotos')){
       return false;
   }
   
   callFunction = 'showphotos';
   args = new Array(gallery_id,1);
   smarty = 'page/ajax/insertimage_photos';
   returnFunction = 'insertimage_photosCB';
   returnFunctionArgs = '';
   wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs);
}

function insertimage_photosCB(result, id, error){
    var editdummy = document.getElementById('ajax_insertimage_photos');
    editdummy.innerHTML = result;
    
}

function wrinit(){
    document.onkeydown = checkkey;
}

// fix pro MSIE
function fixE(e) {
	if (!e) e = window.event;
	if (!e.which) e.which = e.keyCode;
	return e;
}
function checkkey(e) {
	e = fixE(e);
	if (e.ctrlKey && e.which == 13) {
	   ajax_submit = document.getElementById('ajax_form_submit');
	  if (! ajax_submit){
	       //alert ('odeslat wrform');
           document.wrform.submit();               //sumbit WRform
	   }else{
	       var ajaxfunct = ajax_submit.onclick;
	       //alert ('odeslat ajax');
	       fireClickEvent(ajax_submit);
	       //pressAjaxSave(ajaxfunct);
	       
       }
	}
}

function fireClickEvent(control) { 
    if (document.all){ 
        control.fireEvent("onclick"); 
    }else{ 
        //var clickEvent = window.document.createEvent("MouseEvent"); 
        //clickEvent.initEvent("click", false, true); 
        //control.dispatchEvent(clickEvent);
        //firefox ma smulu, dokud se to nenauci korektne obsluhovat 
    } 
} 


// 3rd party
    // Firebug console debug function
    function printfire(){
        if (document.createEvent){
            printfire.args = arguments;
            var ev = document.createEvent("Events");
            ev.initEvent("printfire", false, true);
            dispatchEvent(ev);
        }
    }
    
    /*
    Copyright (c) 2006 Stuart Colville
    http://muffinresearch.co.uk/archives/2006/04/29/getelementsbyclassname-deluxe-edition/
    
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
    documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
    the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
    and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all copies or substantial 
    portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
    TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
    IN THE SOFTWARE.
    */
    
    function getElementsByClassName(strClass, strTag, objContElm){
        strTag = strTag || "*";
        objContElm = objContElm || document;
        var objColl = (strTag == '*' && document.all) ? document.all : objContElm.getElementsByTagName(strTag);
        var arr = new Array();
        var delim = strClass.indexOf('|') != -1    ? '|' : ' ';
        var arrClass = strClass.split(delim);
        for (i = 0, j = objColl.length; i < j; i++) {
            var arrObjClass = objColl[i].className.split(' ');
            if (delim == ' ' && arrClass.length > arrObjClass.length) continue;
            var c = 0;
            comparisonLoop:
            for (k = 0, l = arrObjClass.length; k < l; k++) {
                for (m = 0, n = arrClass.length; m < n; m++) {
                    if (arrClass[m] == arrObjClass[k]) c++;
                    if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {
                        arr.push(objColl[i]);
                        break comparisonLoop;
                    }
                }
            }
        }
        return arr;
    }
    
    /* END OF COPYRIGHTED CODE */

// TOVARNA.CZ     
    function LTrim( value ) {
        var re = /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");
    }
    
    function RTrim( value ) {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");
    }
    
    function trim( value ) {
        return LTrim(RTrim(value));
    }


    var criticalSection = 0;
    var movedMenu = 0;
    var userMessages = new Array();
    var changeWatch = 0;
    var statusElement = '';
    var mainElement = '';

    function wrajax(callFunction, args, smarty, returnFunction, returnFunctionArgs, notify){
				if(notify == null)
				  notify = true;
				  
        myUrl = url;
        postparams = "wrajaxfunction=" + (callFunction);
        postparams += "&wrajaxsmarty=" + (smarty);
        for (i = 0; i < args.length; i++){
            postparams += "&wrajaxargs[" + i + "]=" + encodeURIComponent(args[i]);
        }
        
        //alert ('wrajax reguest url:'+myUrl+ 'params:'+postparams);
        
        if (window.ActiveXObject){
             httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }else{
             httpRequest = new XMLHttpRequest();
        }
        
        httpRequest.open("POST", myUrl, true);
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4){
                if (httpRequest.status == 200){
                    if (returnFunction != null){
                        var response = httpRequest.responseText;
                        if (response.substring(response.length-7, response.length) == "<ERROR>"){
                            response = response.substring(0, response.length-7);
                            eval(returnFunction + '(response, returnFunctionArgs,1);');
                        }else{
                            eval(returnFunction + '(response, returnFunctionArgs,0);');
                        }
                        
                        //eval(returnFunction + '(response, returnFunctionArgs);');
                    }else{

                    }
                }else{
                    if (httpRequest.status == 401){
                        alert("Chyba při načítání stránky - nepřihlášen, kód chyby: "+ httpRequest.status +":"+ httpRequest.statusText);
                        window.location='?';
                        return false;
                    }
                    alert("Chyba při načítání stránky "+ httpRequest.status +":"+ httpRequest.statusText);
                    return (false);
              }

							criticalSection = 0;
            
	            if(notify)
	            	notifyUser();
            }
            
        }
        httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        httpRequest.setRequestHeader("Content-length", postparams.length);
        httpRequest.setRequestHeader("Connection", "close");
        httpRequest.send(postparams);
    }
    
    function canEnterCritical(who){
        if (criticalSection != 0){
            notifyUser('error','Načítám data, prosím čekejte.');
            return false;
        }else{
            notifyUser('loading','Načítám data, prosím čekejte.');
            criticalSection = 1;
            return true;
        }
    }
    
    function removeLastNotify(){
        if (! criticalSection){
            userMessages.pop();
        }
    }
    
    // sets text and style for notify area
    function notifyUser(type, message, save, deeper, first_load){
        if (message){
            upper = message.toUpperCase() 
            message = upper.substring(0,1) + message.substring(1,message.length)
        }
        if (criticalSection && (save != 'save')){
            return;
        }
        if (!statusElement || !mainElement){
            statusElement = document.getElementById('status');
            //mainElement = document.getElementById('main');
        }
        
        if (first_load){
            var menuItem = userMessages.pop();
            if (menuItem){
                userMessages.push(menuItem);
                return false;
            }
        }
        if (save == 'save'){
            userMessages.push(new Array(type, message));
        }
        if (! message && ! type){
            var menuItem = userMessages.pop();
            if (deeper){
                menuItem = userMessages.pop();
            }
            if (menuItem){
                userMessages.push(menuItem);
                type = menuItem[0];
                message = menuItem[1];
                //alert ('vybiram z puvodnich'+message);
            }
        }
        if (! message){
            message = ' ';
        }
        if (! type){
            type = 'confirm';
        }
        
       
        
        //statusElement.className = type;
        if (statusElement){
            statusElement.innerHTML = message;
            
            if (type =='tip'){
                statusElement.style.color = '#005dbc';
                statusElement.style.background = '#e5effc';
            }
            if (type =='confirm'){
                statusElement.style.color = '#063';
                statusElement.style.background = '#d6ffbb';
            }
            if (type =='error'){
                statusElement.style.color = '#f09';
                statusElement.style.background = '#ffc';
            }
            if (type =='warning'){
                statusElement.style.color = '#f09';
                statusElement.style.background = '#eef6ff';
            }
            if (type =='loading'){
                statusElement.style.color = '#f09';
                statusElement.style.background = '#fff';
            }
        }
    }
  
    // focuses and selects object
    function focusSelect(object){
        object.focus();
        object.select();
    }
    
    // adds specified className to object
    function addClassName(object,addedClassName){ 
        //printfire (object + object.className);
        if (! object) return;
        object.className = object.className + " " + addedClassName; 
        //object.className = addedClassName;
        
    }
    
    // removes specified className from object
    function removeClassName(object,removedClassName){
        var i, curList, newList;
        
        if (! object) return;
        if (object.className == null) return;
        
        newList = new Array();
        curList = object.className.split(" ");
        for(i = 0; i < curList.length; i++){
            if((curList[i] != removedClassName) && (removedClassName)){
                newList.push(curList[i]);
            }
        }
        object.className = newList.join(" ");
    }
    
    // To cover IE 5.0's lack of the push method
    /*Array.prototype.push = function(value) {
      this[this.length] = value;
    }*/

    function inputChange(){
        if (changeWatch == 0){
            notifyUser('warning','Provedli jste změnu, která vyžaduje uložení','save'); 
        }
        changeWatch = 1;
    }
    
    function hideNodeEdit(node){
        ajaxformcall = '';
        object=document.getElementById(node);
        if(object){
            // removeClassName(object,'showme');
            object.className='editdummy';
            object.innerHTML='';
        }
        return false;
    }

    // popup windows | call it: <a href="http://example.com/" onclick="return w(this.href)">
    
    function w(url,type){
        switch(type){
            case 1:
                var directories='yes';
                var toolbar='yes';
                var status='yes';
                var menubar='yes';
                var location='yes';
                var posWidth = 690;
                var posHeight = 720;
                wname = 'galerie';
            break
            case 2:
                var directories='yes';
                var toolbar='yes';
                var status='yes';
                var menubar='yes';
                var location='yes';
                var posWidth = 900;
                var posHeight = 640;
                wname = 'cizi-okno';
            break
            default:
                var directories='no';
                var location='no';
                var menubar='no';
                var status='no';
                var toolbar='no';
                var posWidth = 1044;
                var posHeight = 1044;
                wname = 'galerie-full';
        }
        if(window.screen.availHeight < posHeight){posHeight = window.screen.availHeight;} 
        if(window.screen.availWidth < posWidth){posWidth = window.screen.availWidth;}
        var posLeft = (window.screen.availWidth - posWidth)/2;
        var posTop = (window.screen.availHeight - posHeight)/2;
        var args='scrollbars=yes,resizable=yes,location='+location+',directories='+directories+',status='+status+',menubar='+menubar+',toolbar='+toolbar+',width=' + posWidth + ',height=' + posHeight + ',left=' + posLeft + ',top=' + posTop;
        var win = window.open(url,wname,args);
        if(win){
            win.focus;
            return false;
        } else return true;
    }


// hide or show top add dialog
    function showTopAdd(){
        var TopAdd = document.getElementById('topadd');
        TopAdd.className = "showme";
    }
    
    function hideTopAdd(){
        var TopAdd = document.getElementById('topadd');
        TopAdd.className = "";
    }
