// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function init_dragdrop(){
    DropReceivingElement=function(id,group){
        this.element=new YAHOO.util.DDTarget(id,group)
    };
    DraggableElement = function(id, options) {
        DraggableElement.superclass.constructor.call(this, id, options.group);
        var el = this.getDragEl();
        YAHOO.util.Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent
        this.options=options
        this.goingUp = false;
        this.lastY = 0;
    };

    YAHOO.extend(DraggableElement, YAHOO.util.DDProxy, {

        startDrag: function(x, y) {
            var dragEl = this.getDragEl();
            var clickEl = this.getEl();
            YAHOO.util.Dom.setStyle(clickEl, "visibility", "hidden");
            dragEl.innerHTML = clickEl.innerHTML;
            YAHOO.util.Dom.setStyle(dragEl, "color", YAHOO.util.Dom.getStyle(clickEl, "color"));
            YAHOO.util.Dom.setStyle(dragEl, "background", "url("+clickEl.src+") no-repeat");
            YAHOO.util.Dom.setStyle(dragEl, "border", "1px solid gray");
        },

        endDrag: function(e) {

            var srcEl = this.getEl();
            var proxy = this.getDragEl();
            // Show the proxy element and animate it to the src element's location
            YAHOO.util.Dom.setStyle(proxy, "visibility", "");
            var a = new YAHOO.util.Motion( 
            proxy, { 
                points: { 
                    to: YAHOO.util.Dom.getXY(srcEl)
                }
            }, 
            0.2, 
            YAHOO.util.Easing.easeOut 
        )
            var proxyid = proxy.id;
            var thisid = this.id;

            // Hide the proxy and show the source element when finished with the animation
            a.onComplete.subscribe(function() {
                YAHOO.util.Dom.setStyle(proxyid, "visibility", "hidden");
                YAHOO.util.Dom.setStyle(thisid, "visibility", "");
            });
            a.animate();
            proxy_el=elementById(proxyid)
            proxy_el.innerHTML="";
        },

        onDragDrop:function(e,id){
            // alert(this.request)
            if(!this.req){
                YAHOO.cms.wait.show(); 
                var requestHandler={
                    success: function(r){
                        $( r.argument.caller.options.update.success).update(r.responseText);
                        r.argument.caller.req=null;
                        YAHOO.cms.wait.hide();
                    },
                    failure:function(r){
                        $(r.argument.caller.options.update.failure).update(r.responseText);
                        r.argument.caller.req=null;
                        YAHOO.cms.wait.hide();
                    },
                    argument:{caller:this}
                };
                this.req=YAHOO.util.Connect.asyncRequest('POST', this.options.url, requestHandler,"is_ajax=true");
            }
        }
    });

}
function get_file_uploads(house){
    year=elementById('bill_year').value;
    month=elementById('bill_month').value;
    if(parseInt(house)<1){
        house=elementById('bill_house').value
    }
    if (house>0){
        new Ajax.Request('/object_catalog/house/manage_houses_bills?house='+house+'&year='+year+'&month='+month, 
        {asynchronous:true, evalScripts:true,
            method:'POST', 
            onComplete:function(request){$('house_bills_upload_container_1').update(request.responseText)}
        }); return false;
    }
};
function get_new_row(){
    new Ajax.Request('/object_catalog/house/add_new_bill_row', 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){$('box').insert(request.responseText)}
    }); return false;
};
function send_xls_request(report,house_id,options){
    var house=elementById(house_id).value
    var year=elementById('bill_year').value
    var month=elementById('bill_month').value
    add_ons="";
    for(var i in options){
        add_ons+=i+"="+options[i];
    }
    window.location='/object_catalog/house/download_report?simple=1&ext=xls&report='+report+'&year='+year+'&month='+month+"&house="+house+"&"+add_ons
    /*new Ajax.Request('/object_catalog/house/download_report?report=1&year='+year+'&month='+month+"&house="+house, 
     {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){}
     }); return false;*/
}
function change_meters_table(house){
    new Ajax.Request('/object_catalog/house/change_meters_table?house='+house, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){$('common_meters_table').update(request.responseText);}
    }); return false;
}
function change_paterins(current,meter){
    last=parseFloat(elementById(meter+"_last_value").innerHTML);
    paterins=elementById(meter+"_paterins");
    if(parseFloat(current)>=last){
        paterins.innerHTML=(current-last).toFixed(3)
    }else{
        paterins.innerHTML="Kļūda!"
    }
}
function refresh_image_list(config){
    cfg="read_only="+config.read_only+"&";
    cfg+="pictures=null&";
    cfg+="parent="+config.parent+"&";
    cfg+="parent_id="+config.parent_id+"&";
    cfg+="temp_id="+config.temp_id+"&";
    cfg+="single="+config.single+"&";
    cfg+="pdf="+config.pdf+"&";
    new Ajax.Request('/picture/reload/?'+cfg, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){$('picture_list_container').update(request.responseText)}
    }); return false;
}
function init_wait_element(){
    init_dragdrop();
    if (!YAHOO.cms.wait) {
        YAHOO.cms.wait =  
            new YAHOO.widget.Panel("wait",   
        { width:"240px",  
            fixedcenter:true,  
            close:false,  
            draggable:false,  
            zindex:100000, 
            modal:false, 
            visible:false 
        }  
    ); 
        YAHOO.cms.wait.setHeader("Ielāde, lūdzu uzgaidiet..."); 
        YAHOO.cms.wait.setBody('<img src="/images/icons/ajax-loader.gif" />'); 
        YAHOO.cms.wait.render(document.body); 
    }
}
function change_month(year){
    month=elementById('bill_month').value
    new Ajax.Request('/object_catalog/house/bill_update_months?year='+year+'&month='+month, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){$('bill_month_container').update(request.responseText);get_file_uploads(0);}
    }); return false;
};
function change_year(month){
    year=elementById('bill_year').value
    new Ajax.Request('/object_catalog/house/bill_update_years?year='+year+'&month='+month, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){$('bill_year_container').update(request.responseText);get_file_uploads(0);}
    }); return false;
};
function blur_house_menu_select(obj){
    var parent=obj.parentNode.parentNode;
    var el=parent.childNodes[1];
    parent.childNodes[0].style.display='block';
    if(obj.innerHTML==''){
        parent.childNodes[0].innerHTML='Izvēlieties noklusēto izvēlni';
    }else{
        parent.childNodes[0].innerHTML=obj.options[obj.selectedIndex].innerHTML;
    }
    parent.removeChild(el);
};
function set_menu(menu_item_id){
    //menu_item_id=elementById('house_menu_id').value
    house=elementById('house_id').value
    new Ajax.Request('/object_catalog/house/set_default_e_manager_branch?house_id='+house+"&menu_item="+menu_item_id, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){}
    }); return false;
};
function set_menu_tree(house_id,container){
    // house=elementById('house_id').value
    new Ajax.Request('/object_catalog/house/show_house_menus?house_id='+house_id, 
    {asynchronous:true, evalScripts:true,
        method:'POST', 
        onComplete:function(request){
            var el=document.createElement('span');
            var parent=elementById(container);
            parent.childNodes[0].style.display='none';
            el.innerHTML=(request.responseText);
            parent.appendChild(el);
            for(var i=0;i<el.childNodes.length;i++){
                if(el.childNodes[i].tagName && el.childNodes[i].tagName.toLowerCase()=='select'){
                    el.childNodes[i].focus();
                    break;
                }
            }
        }
    }); return false;
};
function select_all(object){
    var all_checks=document.getElementsByName('list_check[]');
    for(i=0;i<all_checks.length;i++){
        if(object.checked){
            all_checks[i].checked='checked';
        }else{
            all_checks[i].checked='';
        }
    }
}
function setRemoteFormParams(fields){
    for (var i in fields){
                
        if (fields[i].type=='textarea'){
            ed=tinyMCE.get('object_'+fields[i].field);
            val=ed.getContent();
            try{
                edt=tinyMCE.get('translation_'+fields[i].field)
                valt=edt.getContent();
            }catch(e){}
            //alert(valt)
            ta=elementById('object_'+fields[i].field);
            ta.value=val;
            try{
                tat=elementById('translation_'+fields[i].field);
                tat.value=valt;
            }catch(e){}
        }
    }
}
function setDeleteFormParams(){
    var source=document.getElementsByName('list_check[]');
    var dest=elementById('special_remote_delete_form');
    var values=""
    for(var i=0;i<source.length;i++){
        if (source[i].checked){
            values+=source[i].value+","
        }
    }
    dest.value=values
            
}
function insert_row(id,value){
    el=elementById(id);
    row=document.createElement("div");
    row.className="object-remote-list-row";
    row.id="object_remote_list_row_" + Math.random();
    row.innerHTML=value
    el.appendChild(row);
}
function changeOpacity(obj,opacity){
    if (Prototype.Browser.IE){
        obj.style.filter="alpha(opacity="+opacity*100+")";
    }else{
        obj.style.opacity=opacity;
    }
}
function init_picture_title_dialog(id,title,language){
    try{
        f=elementById('pic_title_dialog_form')
        f.action="/picture/save_title/"+id
        el=f.elements[0].value=title || "";
        f.elements[1].value=language || "lv"
    }catch(e){}
    if(!YAHOO.cms.pic_title_dialog){
        var handleSubmit=function(){
            this.submit();
        }
        var handleCancel=function(){
            YAHOO.cms.pic_title_dialog.hide();
        }
        var handleSuccess = function(o) {
            parts=o.responseText.split("\n");
            el=$('normalpicturesthumb_'+parts[0])
            el.title=parts[1]
            el.lang=parts[2]
            
            YAHOO.cms.pic_title_dialog.hide();
	};
	var handleFailure = function(o) {
	}
        
        YAHOO.cms.pic_title_dialog=new YAHOO.widget.Dialog("pic_title_dialog", 
        { width : "300px",
          fixedcenter : true,
          visible : false, 
          constraintoviewport : true
         // buttons : [ { text:"Saglabāt", handler:handleSubmit, isDefault:true },
           //           { text:"Atcelt", handler:handleCancel } ]
        });
        YAHOO.cms.pic_title_dialog.callback = { success: handleSuccess,
						     failure: handleFailure };
	YAHOO.cms.pic_title_dialog.render();
    }
    YAHOO.cms.pic_title_dialog.show();
}
function checkPictureState(event,obj,title,id,language){
    if(Event.isCtrlPressed(event)){
        hidden_element=document.getElementById(obj.id+'_hidden');
        if (hidden_element){
            if(obj.state){
                obj.state=false;
                hidden_element.name="thumb[normal]";
                obj.className="normal-picture-thumb";
                changeOpacity(obj,1);
            }else{
                obj.state=true;
                rec_id=obj.id.split('_')
                rec_id=rec_id[1]
                hidden_element.name="thumb["+rec_id+"]";
                obj.className="deleted-picture-thumb";
                changeOpacity(obj,0.5)
            }   
        }
    }else{
        if(id){
            init_picture_title_dialog(id,title,language);
        }
    }
}

function onPictureChange(obj,address,container,fnc,parent,parent_id){
    
    var pics=document.getElementsByName('mypics');
    var postStr="";
    for (i in pics){
        if (pics[i].state){
            id=pics[i].id.split("_");
            id=id[1];
            postStr+=id+",";
        }
    }
    if (!fnc){
        postStr='pic='+postStr;
        postStr+='&parent='+parent;
        postStr+='&parent_id='+parent_id;
        postStr+='&container='+container;
        if (parent_id<1){
            postStr+='&newrecord=true';
        }
        new Ajax.Request(address, 
        {
            asynchronous:true,
            method:'post',
            parameters:postStr,
            onComplete: function(request){
                $(container).update(request.responseText);
            }
        });
    }else{
        return postStr;
    }
    
}
function elementById(id){
    if (document.getElementById)
        return (document.getElementById(id));
    if (document.all)
        return document.all[id];
    if (document.layers)
        return document.layers[id];
    return false;
}
MenuItemEdit = Class.create();
MenuItemEdit.prototype = {
    initialize: function(menu_name, id,with_picture){
        var text_node = $(menu_name+'_item_name_'+id)
        var item_node = text_node.parentNode
        with_picture=with_picture || false
        if (Element.visible(item_node)){
            Element.hide(item_node)
            this.editor = document.createElement("div")
            this.editor.id = menu_name+"_item_edit_"+id
            this.editor.obj = this;
            this.editor.textNodePrefix = menu_name+'_item_name_' 
            this.editor.entryId = id
            this.lineEdit = document.createElement("input")
            this.lineEdit.type = "text"
            this.lineEdit.size = 10
            this.lineEdit.value = text_node.innerHTML
            this.editor.appendChild(this.lineEdit)
            this.okBtn = document.createElement("img")
            this.okBtn.src = "/images/icons/button_ok.png"
            this.editor.appendChild(this.okBtn)
            this.cancelBtn = document.createElement("img")
            this.cancelBtn.src = "/images/icons/button_cancel.png"
            this.editor.appendChild(this.cancelBtn)
            if (with_picture){
                this.picture_container=document.createElement("div")
                obj_id=menu_name+'_menu_item_edit_picture_container_'+id
                this.picture_container.id=obj_id
                this.editor.appendChild(this.picture_container)
                new Ajax.Request('/picture/ajax_container', 
                {asynchronous:true,
                    onComplete: function(request){
                        $(obj_id).update(request.responseText);
                    },
                    parameters:'parent=MenuItem&parent_id='+id
                });
            }
                
            item_node.parentNode.appendChild(this.editor)
                
            this.okListener     = this.onOk.bindAsEventListener(this);
            this.cancelListener = this.onCancel.bindAsEventListener(this);
            Event.observe(this.okBtn,       'click', this.okListener);
            Event.observe(this.cancelBtn,   'click', this.cancelListener);
        }
    },
        
    onOk: function(){
        new Ajax.Updater(this.editor.textNodePrefix+this.editor.entryId, '/admin/menu/rename/'+this.editor.entryId+'?name='+this.lineEdit.value);
        this.dispose();
    },
        
    onCancel: function(){
        this.dispose();
    },
        
    dispose: function(){
        Element.show($(this.editor.textNodePrefix+this.editor.entryId).parentNode);
        if (this.editor.parentNode) Element.remove(this.editor);
        this.editor = null;
        Event.stopObserving(this.okBtn, 'click', this.okListener);
        Event.stopObserving(this.cancelBtn, 'click', this.cancelListener);
    }
}
    
ListItemEdit = Class.create();
ListItemEdit.prototype = {
    /*
     * Izveido ievades objektu
     * @method new
     * @param {String} id Objekta id, piemēram, user.id.to_s
     * @param {String} prefix HTML objekta id prefikss, piemēram, <span id='user_1'> prefix='user_'
     * @param {String} method Controller method to call. Example, '/admin/user/show'
     * @param {Boolean} outter Updatable object is other no editor object.
     * @param {String} outter_id Object to update id, NOT self 
     */
    initialize: function(id,prefix,method,outter,outter_id){
        var text_node = $(prefix+id)//"list_item_name_"+
        inline_prefix="list_item_edit_"
        var item_node = text_node
        this.outter=outter || false
        this.outter_id=outter_id || false
        this.method=method //metode kuru izpildīt kad beigta rediģēšana
        editorSize=this.getWidth(item_node.id)/9
        var chEl=Element.childElements(prefix+id)
        var old_el=$(inline_prefix+prefix+id)
        if (Element.visible(text_node) && chEl.indexOf(old_el)<0){ 
            this.lineEdit = document.createElement("input")
            this.lineEdit.type = "text"
            this.lineEdit.size = editorSize
            this.lineEdit.value = text_node.innerHTML
            this.lineEdit.id=inline_prefix+prefix+id
            this.oldValue=text_node.innerHTML
            text_node.innerHTML="";
                
            this.entryId=id
            this.textNodePrefix=prefix
            item_node.appendChild(this.lineEdit)
            //item_node.appendChild(this.editor)
            this.blurListener=this.onBlur.bindAsEventListener(this);
            Event.observe(this.lineEdit,'blur',this.blurListener);
            this.lineEdit.focus();
        }
    },
    /*
     * Create Ajax Update when editor lost focus
     * @method onBlur
     */
    onBlur:function(){
        if (this.outter){
            update_id=this.outter_id;
        }else{
            update_id= this.textNodePrefix+this.entryId
        }
        
        if (this.lineEdit.value!=this.oldValue){
            new Ajax.Updater(update_id, this.method+"/"+this.entryId+'?value='+this.lineEdit.value+'&oldValue='+this.oldValue);
        }else{
            $(update_id).innerHTML=this.oldValue
        }
        this.dispose();
    },
    /*
     * Destroy input element
     * @method dispose
     */
    dispose: function(){
        //Element.show($( this.editor.textNodePrefix+this.editor.entryId));
        if (this.lineEdit.parentNode){ try{Element.remove(this.lineEdit)}catch(e){};}
        this.lineEdit = null;
        try{
            Event.stopObserving(this.lineEdit,'blur',this.blurListener);
        }catch(e){}
    },
    /*
     * Return element width
     * @method getWidth
     * @param {String} elemID ID of DOM object that width need to get
     * @return {Float} Element width or 0 if element doesn't exists
     */
    getWidth:function(elemID){
        var elem=document.getElementById(elemID);
        if (elem){
            xPos = elem.offsetWidth;
        }else{
            xPos=0;
        }
        return xPos;
    }
}
AutoUploadForm=Class.create();
AutoUploadForm.prototype= {
    /*
     * Inicialize file auto upload form
     * @method initialize
     * @param {String} action Ruby action to call
     * @param {String} form_id HTML form including input field with type file id
     * @param {String} element_id HTML input field element id
     * @param {String} target_id DOM element to update
     * @param {Boolean} overwrite Either add html or replace
     */
    initialize:function(action,form_id,element_id,e,target,overwrite){
        this.form_id=form_id;
        this.target_id=target || false;
        this.action=action;
        observable_event=e || 'change'
        this.overwrite=overwrite;
        temp_input=elementById(element_id);
        //if (temp_input.type=='file'){
        YAHOO.util.Event.on(element_id, observable_event, this.doUpload,this,true);	
        //}else{
        //	throw ("Observable object type isn't file");
        //}
    },
    doUpload:function(e){
        YAHOO.util.Connect.setForm(this.form_id, true);
        
        var uploadHandler={
            upload: function(o){
                //var a=1;
                //alert(o.responseText)
            },
            argument:{caller:this}
        };
        upReq=YAHOO.util.Connect.asyncRequest('POST', this.action, uploadHandler);
    }
}

ConnectionEdit = Class.create();
ConnectionEdit.prototype = {
    initialize: function(id, menu_name, controller, action,tables){
        var text_node = $(menu_name+'_item_name_'+id)
        var item_node = text_node.parentNode
        this.editor = document.createElement("div")
        this.editor.id = menu_name+"_item_connection_edit_"+id
        this.editor.obj = this;
        this.editor.textNodePrefix = menu_name+'_item_name_' 
        this.editor.entryId = id
        this.editor.menuName = menu_name
        this.controllerLabel = document.createTextNode("controller:")
        this.editor.appendChild(this.controllerLabel)
        
        this.controllerEdit = document.createElement("select")
        for(var i=0;i<tables.length;i++){
            var opt=document.createElement("option")
            
            if (controller==tables[i][1]){
                opt.selected="selected"
            }
            opt.value=tables[i][1]
            opt.innerHTML=tables[i][0]
            this.controllerEdit.appendChild(opt)
        }
        // this.controllerEdit.type = "text"
        // this.controllerEdit.size = 10
        //this.controllerEdit.value = controller
        this.editor.appendChild(this.controllerEdit)
        this.actionLabel = document.createTextNode("action:")
        this.editor.appendChild(this.actionLabel)
        this.actionEdit = document.createElement("input")
        this.actionEdit.type = "text"
        this.actionEdit.size = 10
        this.actionEdit.value = action
        this.editor.appendChild(this.actionEdit)
        this.okBtn = document.createElement("img")
        this.okBtn.src = "/images/icons/button_ok.png"
        this.editor.appendChild(this.okBtn)
        this.cancelBtn = document.createElement("img")
        this.cancelBtn.src = "/images/icons/button_cancel.png"
        this.editor.appendChild(this.cancelBtn)
        item_node.parentNode.appendChild(this.editor)
        
        this.okListener     = this.onOk.bindAsEventListener(this);
        this.cancelListener = this.onCancel.bindAsEventListener(this);
        Event.observe(this.okBtn,       'click', this.okListener);
        Event.observe(this.cancelBtn,   'click', this.cancelListener);
    },
    onOk: function(){
        new Ajax.Updater(this.editor.menuName+'_configure_menu_items', '/admin/menu/set_action/'+this.editor.entryId+'?ctr='+this.controllerEdit.value+'&act='+this.actionEdit.value);
        this.dispose();
    },
    
    onCancel: function(){
        this.dispose();
    },
    
    dispose: function(){
        if (this.editor.parentNode) Element.remove(this.editor);
        this.editor = null;
        Event.stopObserving(this.okBtn, 'click', this.okListener);
        Event.stopObserving(this.cancelBtn, 'click', this.cancelListener);
    }
}
