function is_object (mixed_var) {

    if (Object.prototype.toString.call(mixed_var) === '[object Array]') {        return false;
    }
    return mixed_var !== null && typeof mixed_var == 'object';
}

function isset () {
   var a = arguments,
        l = a.length,        i = 0,
        undef;
 
    if (l === 0) {
        throw new Error('Empty isset');    }
 
    while (i !== l) {
        if (a[i] === undef || a[i] === null) {
            return false;        }
        i++;
    }
    return true;
}

var inline_editors=new Array();
var dialog='';
var canclose=false;



function jq_frame_dlg(target_url,obj,action){
        canclose=false;
        var r_url=' ';
        switch(action){
                case 'new':
                break;
                default:
                r_url=target_url;
                break;
        }
        var ret=jQuery.FrameDialog
        //create will make an iframe based on the url, other options are
        //    passed to jQueryUI's dialog command.
            .create({
            url: r_url,
            title: obj.name,
            //width: $('#fix').width() ? $('#fix').width() : $('#main').width(),
            //height: $('#fix').height() ? $('#fix').height() : $('#main').height(),
            width: Math.round($(window).width()*0.75),
            height: Math.round($(window).height()*0.85),
            buttons: {},

           })
           .bind('dialogbeforeclose', function(event, ui) {
               if(canclose){
                        switch(action){
                        case 'upload':
                        case 'edit':
                        case 'new':
                                $.ez( 'ezvs::clearobjectcache::'+obj.object_id,{},function(data){
                                                        if(data.content){
                                                                this.lastresult=data.content;
                                                                if(!data.content.status){
                                                                    
                                                                }else{

                                                                }
                                                        }

                                                        window.location=window.location;
                                                        
                                                   }
                                );
                               
                        break;
                        default:
                        break;
                        }
                        return true;
                
                }else{
                     switch(action){
                        case 'new':
                        case 'edit':
                               // alert('Dont use close button! Please end session inside dialog!!!');
                               // return false;
                               return true;
                        break;
                        default:
                                window.location=window.location;
                                return true;
                        break;
                        }
                        
                }
            })

            //create returns a jQuery object for the dialog created,
            //    from here you can do your event binding.

            .bind('dialogcreate', function(event, ui) {
            // alert("result:" + event.result);
            });

            dialog=ret;
            
            switch(action){
                                case 'new':
                                        var node_id=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','NodeID')
                                                     .attr('value',obj.node_id);
                                        var c_node_id=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','ContentNodeId')
                                                     .attr('value',obj.node_id);
                                        var c_object_id=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','ContentObjectId')
                                                     .attr('value',obj.object_id);
                                        var class_iden=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','ClassIdentifier')
                                                     .attr('value',obj.class_identifier);
                                         var lang_id=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','LanguageCode')
                                                     .attr('value',obj.language);            
                                        var action_btn=$('<input />')
                                                     .attr('type','hidden')
                                                     .attr('name','NewButton')
                                                     .attr('value','NewButton');       
                                        var form=$("<form ></form>")
                                                  .attr('action',target_url+'/content/action')
                                                  .attr('method','post')
                                                  .attr('id','form_actin_'+obj.div_id)
                                                  .attr('target',ret.attr('id')+'-VIEW')
                                                  .append(node_id)
                                                  .append(class_iden)
                                                  .append(lang_id)
                                                  .append(c_node_id)
                                                  .append(c_object_id)
                                                  .append(action_btn)
                                        //console.log(form);          
                                        $('#dialog_'+id).append(form);
                                        form.submit();
                                break;
           }                                          
}

function generate_editors(editors){
        //console.log(editors);
        $.each(editors,function(i,obj){
                               id=obj.div_id
                               
                               var edit_button=$("#editbutton_"+id);
                               var new_button=$("#newbutton_"+id);
                               var del_button=$("#removebutton_"+id);
                               var upload_button=$("#uploadbutton_"+id);
                               if(edit_button){
                                        //console.log(edit_button);
                                        edit_button.click(function(){
                                                //$('#dialog_'+id).html(data.content);
                                               
                                               //jq_frame_dlg('/layout/set/inline_edit/content/edit/'+obj.object_id+'/'+obj.version+'/'+obj.language,obj,'edit');
                                               jq_frame_dlg('/layout/set/inline_edit/content/edit/'+obj.object_id,obj,'edit');

                                        });
                               }

                             

                               if(new_button){
                                        new_button.click(function(){

                                               jq_frame_dlg('/layout/set/inline_edit',obj,'new');

                                        });
                               }

                               if(upload_button){
                                        upload_button.click(function(){

                                               jq_frame_dlg('/layout/set/inline_edit/ezmultiupload/upload/'+obj.node_id,obj,'upload');

                                        });
                               }

                               if(del_button){
                                        del_button.click(function(){
                                         $('#dialog_'+id).dialog({
                                                width: $('#fix').width() ? $('#fix').width() : $('#main').width(),
                                                modal: true,
                                                open: function(){
                                                        $(this).html('<h2>Delete this object?</h2>');
                                                },
                                                buttons: {
                                                        "OK": function(){
                                                                $.ez( 'ezvs::removenodes::'+obj.node_id,{},function(data){
                                                                        if(data.content){
                                                                                if(!data.content.status){
                                                                                //error
                                                                                }else{
                                                                                        $('#dialog_'+id).dialog("close");
                                                                                        window.location=obj.parent_url;
                                                                                 
                                                                                }
                                                                        }
                                                                });
                                                        },
                                                        "Cancel": function(){
                                                                        $('#dialog_'+id).dialog("close");
                                                        }
                                                }
                                          });

                                        });
                               }
                                
                                
                        }
        );
}



function JSEZContent(){

        this._cansubmit=false;
        this._must_be_validate=false;
        this._unvalidate_id='validation-status';
        this._is_logger=false;
        this._formid='';
        this._h_element=$("#"+this._unvalidate_id);
        this.lastresult='';
        this.status=false;
        this.callend=true;
        

this.logger=function(str){
        if(this._is_logger){
                console.log(str);
        }
};

this.found_tinyMCE=function(){
           if(isset(window.tinyMCE)){
                return is_object(window.tinyMCE);
           }
           return false;
};

this.__get_form_data=function(formid){
        if(this.found_tinyMCE()){
                window.tinyMCE.triggerSave();
                this.logger('Found tinyMCE');
        }
        return $("#"+formid).serializeArray();
};

this.must_be_validate=function(){
        this._must_be_validate=true;
};


this.__pre_serialize=function(formid){
                $("#"+formid).bind('form-pre-serialize', function(e) {
                        tinyMCE.triggerSave();
                });
};
        
this.__empty_h_element=function(){
                this._h_element.empty();
};
               
this.__write_unvalidated_content=function(data){
                //var h_element=$("#"+unvalidate_id);
                 this._h_element.empty();
                                                             
                 this._h_element.append('<h2>Validation failed</h2>');
                 this._h_element.append('<ul>');
                 var str='';
                 jQuery.each(data.content['unvalidated-attributes'], function(i, field){
                           str+='<li><b>'+field.name + "</b>: "+field.description+'</li>';
                 });
                 this._h_element.append(str);
                 this._h_element.append('</ul>');
};
        
this.validate=function(formid,objectid,versionid,editlang){
                //alert(must_be_validate);
                if(!this._must_be_validate) return true;

                var form_data = this.__get_form_data(formid);
                
                $.ez( 'ezvs::validateobject::'+objectid+'::'+versionid+'::'+editlang,form_data,function(data){
                                                        if(data.content){
                                                        //$.debug(data.content);
                                                                this.__empty_h_element()
                                                                if(!data.content.isValid){
                                                                     this.__write_unvalidated_content(data);   
                                                                }else{
                                                                    this._cansubmit=true;
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
                   this.logger('Can submit:'+ true);
                   return this._cansubmit;

};

this.validate_and_publish=function(formid,objectid,versionid,editlang){
                this.callend=false;
                var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::publish::'+objectid+'::'+versionid+'::'+editlang,form_data,function(data){
                                                        if(data.content){
                                                        //$.debug(data.content);
                                                                this.__empty_h_element()
                                                                if(!data.content.isValid){
                                                                     this.__write_unvalidated_content(data);
                                                                     this.status=false;   
                                                                }else{
                                                                    //$.debug(data.content['publish-result']);
                                                                    this.status=true;
                                                                }
                                                                
                                                                
        
                                                        }
                                                        
                                                     	//if(FormWindow)
                                                    	//	after_update(FormWindow);
                                                          this.callend=true;      
                                                                
                        
                                                   }     
                 
                 
                   );

                   return this.status;
};



this.directpublish=function(formid,objectid,versionid,editlang){

                var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::directpublish::'+objectid+'::'+versionid+'::'+editlang,form_data,function(data){
                                                        if(data.content){
                                                        //$.debug(data.content);
                                                                this.__empty_h_element()
                                                                if(!data.content.isValid){
                                                                     this.__write_unvalidated_content(data);   
                                                                }else{
                                                                    //$.debug(data.content['publish-result']);   
                                                                }
                                                                
                                                                
        
                                                        }
                                                        

                        
                                                   }     
                 
                 
                   );
};
this.validate_and_storedraft=function(formid,objectid,versionid,editlang){

                 var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::storedraft::'+objectid+'::'+versionid+'::'+editlang,form_data,function(data){
                                                        if(data.content){
                                                        //$.debug(data.content);
                                                                this.__empty_h_element()
                                                                if(!data.content.isValid){
                                                                     this.__write_unvalidated_content(data);   
                                                                }else{
                                                                    //$.debug(data.content['publish-result']);   
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
};

this.removeDraft=function(formid,objectid,versionid,editlang){

                 var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::removedraft::'+objectid+'::'+versionid+'::'+editlang,form_data,function(data){
                                                        if(data.content){
                                                          	if(!data.content.status){
								   //error
                                                                }else{
                                                                    //$.debug(data.content['publish-result']);   
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
};

this.search=function(formid){
                var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::search',form_data,function(data){
                                                        if(data.content){
                                                                if(!data.content.status){
                                                                   //error
                                                                }else{
                                                                    //$.debug(data.content);
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
};

this.updateattributes=function(formid,objectid){
                var form_data = this.__get_form_data(formid);
                 $.ez( 'ezvs::updateattributes::'+objectid,form_data,function(data){
                                                        if(data.content){
                                                                $.debug(data.content);
                                                                if(!data.content.status){
                                                                   //error
                                                                }else{
                                                                    //$.debug(data.content);
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
};

this.loadnode=function(objectid){
                var attribute_arg='';
                 result='';
                
                 $.ez( 'ezvs::load::'+objectid,{},function(data){
                                                        if(data.content){
                                                                this.lastresult=data.content;
                                                                if(!data.content.status){
                                                                   //error
                                                                }else{
;
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );

                   //return result;
};

this.clearobjectcache=function(objectid){
                 $.ez( 'ezvs::clearobjectcache::'+objectid,{},function(data){
                                                        if(data.content){
                                                                this.lastresult=data.content;
                                                                if(!data.content.status){
                                                                   //error
                                                                }else{

                                                                }
                                                        }
                                                   }
                   );
};

this.uploadfiles=function(formid,parentobjectid){
                var form_data = this.__get_form_data(formid);
                $.ez( 'ezvs::uploadfiles::'+parentobjectid,form_data,function(data){
                                                        if(data.content){
                                                                if(!data.content.result){
                                                                   $.debug(data.content);
                                                                }else{
                                                                    $.debug(data.content);
                                                                }
                                                                

        
                                                        }
                        
                                                   }     
                   );
};

this.ajaxupload=function(f_action,button_id,status_id){
        $(function(){  
                var btnUpload=$('#'+button_id);
                var status=$('#'+status_id);
                new AjaxUpload(btnUpload, {  
                action: f_action,  
            //Name of the file input box  
                name: 'uploadfile',  
                onSubmit: function(file, ext){  
  
                    return true;  
                 
                status.text('Uploading...');  
            },  
            onComplete: function(file, response){  
                //On completion clear the status  
                status.text('');  
                //Add uploaded file to list  
                status.append(response);
            }  
        });  
    });  
};

}

var jsc=new JSEZContent();

 $(document).ready(function(){
        generate_editors(inline_editors);
 })

