/**@author Pavan sharma<pavan.sharma@acapteam.com> 04/05/2010
*  @package:ERK Module
*  @description:script for doing operation attachments related functionalities for  Electronic record keeping Module
*  @Module:Electronic Record Keeping
*/   

var objArray=new Array();//hold attachment form value in object under javascript 
var selectedAttachment='';//hold comma separated value of selected attachment 
var selectedCount=0;//hold count of selected attachment
var newCount=0;//new count
var selectedNewAttachment=''; //selected dupplicate attachment
var builtInAttachment='';
var isImageUploaded=0; //check whether image is uploaded
var operationAttachmentId='';//hold operation attachment id in edit mode
var editMode=0;
/**
* @description:function to select attachment item from add/edit operation page in Electronic record keeping UI
* @return string selectedAttachment in comma separated value
*/
$(function() {       
    $("#operation_selectable").selectable({
        stop: function(){
            selectedAttachment ='';
            var selectArr=new Array();
            var newArr=new Array();//will hold new atachment html id
            var result='';
            var index=''; //
            var result=false;  //test for new attachment
            var patt=/new/;
            $(".ui-selected", this).each(function(){
                //var index = $("#operation_selectable li").index(this);
                //index = $("#operation_selectable li").attr("id");

                result=patt.test($(this).attr('id'));
                if(!result){ 

                    index=$(this).attr('id');
                    index=index.replace("attachment_","");                 
                    selectArr.push(index); 
                }
                else{
                    index=$(".temp_attachment",this).html();

                    newArr.push(index);
                }

                //alert(selectArr);
            });
            selectedCount=selectArr.length;
            selectedAttachment=selectArr.join(",");
            newCount= newArr.length;
            selectedNewAttachment=newArr.join(",");
            
        }
    });

    $("#built_in_selectable").selectable({
        stop: function(){
            builtInAttachment ='';
            var selectBuiltArr=new Array();

            var result='';
            var index=''; //           

            $(".ui-selected", this).each(function(){
                //var index = $("#operation_selectable li").index(this);
                //index = $("#operation_selectable li").attr("id");



                index=$(this).attr('id');
                index=index.replace("built_attachment_","");                 
                selectBuiltArr.push(index); 



                //alert(selectArr);
            });
            //selectedBuiltCount=selectBuiltArr.length;
            builtInAttachment=selectBuiltArr.join(",");

        }
    });
    addToolTip('operation_selectable');//from tooltip.js
    showBuiltInToolTip('built_in_selectable');//for built in display of note
    
    setAttachmentView();
    addShowHideMainFunction();
    addToolTipByClass();//add tooltip 
    operationTooltip();
    addShowHideFunction();
    $(":input,.swapimage2").bind("click",mainPositionSetter);
    $("a,img").bind("click",delayTimeout);
    $(window).resize(mainPositionSetter)
    $accessInitial=1;$tabInitial=1;
    $(":input").each(function(){
        /*$(this).attr("tabindex",$tabInitial);
        $(this).attr("accesskey",$accessInitial);
         $tabInitial++;
         $accessInitial++;  */
    })
});
//create attachment class for javascript
var Attachment=function(operation_id,db_index){

    this.operation_id=operation_id;//get OperationId
    this.db_index= db_index;  //get db_index for current module
    this.xajaxJsonResponse;


}
/** 
*   @description:show attachmentform ERK
*    disable buttons
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.show=function(obj,attachmentId){
    $('#attachment_form_div'+attachmentId+'').show();
    $('.attachment_button').each(function(i){
        if($(this).attr("id")==$(obj).attr("id")){
            //Prevent disabling of calling button
        }else{
            $(this).attr("disabled","disabled");
        }  
    }         
    );
    if(attachmentId==''){
        populateCategory(attachmentId);
    }
     mainPositionSetter();
}

/** 
*   @description:disable buttons
*    
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.disableButton=function(obj,attachmentId){

    $('.attachment_button').each(function(i){
        if($(this).attr("id")==$(obj).attr("id")){
            //Prevent disabling of calling button
        }else{
            $(this).attr("disabled","disabled");
        }  
    }
    )
}

/**
* @description :show Hide Input text box for user
* @param string attachmentId
* @param string inputId input number
*/

Attachment.prototype.showHideInput=function(inputId,attachmentId){

    if($('#input_check_'+inputId+attachmentId+':checked').val()==null){
        // hide textbox using span id
        $('#input_label_span_'+inputId+attachmentId+'').hide();
        //empty textbox value
        $('#input_text_'+inputId+attachmentId+'').val('');

    }else{
        //show textbox 
        $('#input_label_span_'+inputId+attachmentId+'').show();           

    }   
     mainPositionSetter();
}


/** 
*   @description:show Edit from
*    disable buttons
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/

/*Attachment.prototype.showEdit=function(obj,attachmentId,mode){
    //alert(selectedAttachment);
    if(selectedAttachment!=''){
        //this.hide(attachmentId); //deprecated
        if(mode=='View'){
            xajax_viewAttachment(this.db_index,selectedAttachment);
        }else{
            this.disableButton(obj,attachmentId);  
            xajax_editAttachment(this.db_index,selectedAttachment);
        } 

    }else{
        alert("Please select attachment ");
    }

}*/

Attachment.prototype.showEdit=function(obj,attachmentId,mode){
    //alert(selectedAttachment);
    //alert(selectedAttachment);
    //alert(selectedNewAttachment);  
    if((selectedAttachment!='') || (selectedNewAttachment!='')){
        //this.hide(attachmentId); //deprecated
        if(mode=='View'){
            xajax_viewAttachment(this.db_index,selectedAttachment);
        }else{
            this.disableButton(obj,attachmentId);  
            xajax_editAttachmentTemp(this.db_index,$.toJSON(objArray),selectedAttachment,selectedNewAttachment);
        } 

    }else{
        alert("Please select attachment ");
    }

}
/** 
*  function showBuiltIn 
*   @description:show built in attachment
*    disable buttons
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.showBuiltIn=function(obj,attachmentId){
    $('#add_built_in_div').show();
    this.disableButton(obj,attachmentId); 
    mainPositionSetter(); 

}
/** 
*  function hideBuiltIn 
*   @description:show built in attachment
*    disable buttons
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.hideBuiltIn=function(){
    $('#add_built_in_div').hide();
    this.enableButton();
    mainPositionSetter();

}
/**
* function addBuiltIn
* @description :add built in data  to attachment
* 
*/
Attachment.prototype.addBuiltIn=function(){
    xajax_getJsonDataForAttachment(this.db_index,builtInAttachment,this.operation_id,1) ;//create attachment from built in attachment
    $('#add_built_in_div').hide();
    this.enableButton();
    mainPositionSetter();
}


/** 
*    @description Hide form for ERK enabling buttons
*    @param string attachmentId
*/
Attachment.prototype.hide=function(attachmentId){
    //disable form
    $('#attachment_form_div'+attachmentId+'').hide();
    if(attachmentId!=''){
        selectedCount--; //decrease count for enabling button logic
        if(selectedCount==0){
            this.enableButton(); //enable controls
        }
    }else{
        this.enableButton(); //enable controls
    }  
     mainPositionSetter();    
}
/** 
*    @description enable disable buttons  and hide form input
*    
*/
Attachment.prototype.enableButton=function(){

    $('.attachment_button').each(function(i){

        $(this).attr("disabled","");

    })
}
/**
*  @description :Attachment class function add ,operation related to add
*  @param string attachmentId
*  @assign :json value to attachment_json form element 
*/

Attachment.prototype.add=function(attachmentId){
    //create object AttachmentData for add attachment and assign form values
     //alert(attachmentId);
    var attachmentData =new AttachmentData(attachmentId,this.operation_id);
    //alert($.toJSON(attachmentData));
    if(attachmentId==''){
        attachmentData.operation_attachment_id=randomNo(10001,65534);
        //alert(randomNo(10001,65534));
        objArray.push(attachmentData);
        var strCategoryArr=strCategory.split(",");
        strCategoryArr.push(attachmentData.operation_attachment_category);
        strCategoryArr=uniqueThis(strCategoryArr);
        strCategory=strCategoryArr.join(",");
        //New Addition to update category from dyanamic addition
        //todo unbind keydown event
        //populateCategory(attachmentId);
        //encode to json for decoding on process page  
        var attachmentJson=$.toJSON(objArray);
       //$('#errLog').html(attachmentJson);
        $('#attachment_json').val(attachmentJson);
        //alert($('#attachment_json').val());
        // attachmentData.memberTypeArr. 
        this.hide(attachmentId); 

        this.enableButton(); //enable controls for add button clicked
        //$('#operation_selectable').append('<li id="new_attachment_'+newCount+'_'+attachmentData.operation_attachment_id+'" style="background-color:#00AFF7"><div class="temp_attachment">'+attachmentData.operation_attachment_name+'</div> <span style="display:none">'+attachmentData.operation_attachment_notes+'</span></li>');
        $('#operation_selectable').append('<li id="attachment_'+attachmentData.operation_attachment_id+'" style="background-color:#00AFF7"><div class="temp_attachment">'+attachmentData.operation_attachment_name+'</div> <span style="display:none">'+attachmentData.operation_attachment_notes+'</span></li>');
        newCount++;
        addToolTip('operation_selectable');//from tooltip.js
        this.reset('attachment_form_div');

    }/*else if(parseInt(attachmentId)>10000){ //attachmentid above 10000 is assumed as temp attachment
       // alert(attachmentId);
        this.processData(attachmentData,0);  
        var attachmentJson=$.toJSON(objArray);
        //alert(attachmentJson);
        $('#attachment_json').val(attachmentJson);
        //selectedCount--;

        $('#attachment_'+attachmentData.operation_attachment_id+'').html(attachmentData.operation_attachment_name+ '<span style="display:none">'+attachmentData.operation_attachment_notes+'</span>');

        //alert(selectedCount) ;
        // if(selectedCount==0){
        // alert("in");
        //  this.enableButton(); //enable controls for edit button clicked
        //}   
        this.hide(attachmentId); 
    } */
    else{
        //alert(attachmentId);
        //alert(selectedCount) ;
        this.processData(attachmentData,1);  
        var attachmentJson=$.toJSON(objArray);
        //alert(attachmentJson);
        $('#attachment_json').val(attachmentJson);
        //selectedCount--; 
        $('#attachment_'+attachmentData.operation_attachment_id+'').html(attachmentData.operation_attachment_name+ '<span style="display:none">'+attachmentData.operation_attachment_notes+'</span>');

        //alert(selectedCount) ;
        // if(selectedCount==0){
        // alert("in");
        //  this.enableButton(); //enable controls for edit button clicked
        //}   
        this.hide(attachmentId); 

    }    
}


/**
* function toggleActive
* 
* toggle active property of selected attachment
* 
*/
Attachment.prototype.toggleActive=function(){
    var arrSelected=selectedAttachment.split(",");
    var arrSelectedNew=selectedNewAttachment.split(",");
    for(i=0;i<objArray.length;i++){
        var attachmentObj= objArray[i];


        if(jQuery.inArray(attachmentObj.operation_attachment_id, arrSelected)!=-1){
            //change attachment status  of loaded attachment
            attachmentObj.operation_attachment_active=attachmentObj.operation_attachment_active=='0'?1:0;
            //alert(attachmentObj.operation_attachment_active);
            objArray[i]= attachmentObj;
        }  

        if(jQuery.inArray(attachmentObj.operation_attachment_id, arrSelectedNew)!=-1){
            //change attachment status of newly added attachment
            attachmentObj.operation_attachment_active=attachmentObj.operation_attachment_active=='0'?1:0;

            objArray[i]= attachmentObj;
        }                          

    }

    $(".ui-selected",$("#operation_selectable")).each(function(){
        //alert(this.id);
        var testClass=/inactive-attachment/
        var result=testClass.test(this.className);
        if(result){
            // alert("MAtch" + this.className.replace("inactive-attachment",""));
            this.className=this.className.replace("inactive-attachment","");
             $('.operation_'+this.id).attr("class",$('.operation_'+this.id).attr("class").replace("inactive-attachment",""));
            //alert(this.className);

        }
        else{
            // alert(" UnMATCH "+this.className);
            this.className=this.className + ' inactive-attachment';
            $('.operation_'+this.id).attr("class",$('.operation_'+this.id).attr("class") + ' inactive-attachment');
            //alert(this.className);
        }
    } );


    //$('#show_inactive_attachment').attr('checked','checked');
    //$('#show_inactive_attachment').trigger('onclick');//trigger onclick function for inactive attachment display else it will hide
    var attachmentJson=$.toJSON(objArray); //json encode the whole object array
    $('#attachment_json').val(attachmentJson); //assign it to html element for postback



}

/**
*  @description duplicate existing attachment
*  call xajax_getJsonDataForAttachment fn
*  
*/

Attachment.prototype.duplicate=function(){
    //alert(strJson);
    //call xajax function
    xajax_getJsonDataForAttachmentTemp(this.db_index,$.toJSON(objArray),selectedAttachment,this.operation_id,0) ;

} 
/**
*  function processDuplicate
*  @param string strJson(json encoded data)
*  
*/
Attachment.prototype.processDuplicate=function(strJson){

    var attacmentJsonObj=$.evalJSON(strJson); //eval json encoded data as javascript object
    attacmentJsonObj.operation_attachment_id=randomNo(10001,65534); //assign random attachmentId
    var duplicateAttachmentId=attacmentJsonObj.operation_attachment_id;  
    
    //attacmentJsonObj.operation_attachment_id='';//clear attachmentId for insert
    attacmentJsonObj.operation_id=this.operation_id;
    objArray.push(attacmentJsonObj); //push that object in object array
    var attachmentJson=$.toJSON(objArray); //json encode the whole object array
    $('#attachment_json').val(attachmentJson); //assign it to html element for postback

    //class="ui-widget-content"
    // $('#operation_selectable').append('<li id="new_attachment_'+newCount+'_'+duplicateAttachmentId+'" style="background-color:#00AFF7"><div class="temp_attachment">'+attacmentJsonObj.operation_attachment_name+'</div><span style="display:none">'+attacmentJsonObj.operation_attachment_notes+'</span></li>');
    $('#operation_selectable').append('<li id="attachment_'+duplicateAttachmentId+'" style="background-color:#00AFF7"><div class="temp_attachment">'+attacmentJsonObj.operation_attachment_name+'</div><span style="display:none">'+attacmentJsonObj.operation_attachment_notes+'</span></li>');
    newCount++;
    addToolTip('operation_selectable');//from tooltip.js

}
/**
*  function processData
*  @param object attachmentData data(of attachment)
*  use in add function in edit mode
*/
Attachment.prototype.processData=function(attachmentData,byId){


    var arrayObject;
    for(i=0;i<objArray.length;i++){
        arrayObject=objArray[i];
        //alert(arrayObject.operation_attachment_id);
        if(byId==0){
            //alert(arrayObject.operation_attachment_name+'---'+attachmentData.operation_attachment_name);
            /*if(arrayObject.operation_attachment_name==attachmentData.operation_attachment_name){
                 //alert(attachmentData);
                 //@todo fix bug when  attachment name is changed
                objArray[i]=attachmentData;
            }     */

        }else{
            //alert(arrayObject.operation_attachment_id+'---'+attachmentData.operation_attachment_id);
            if(arrayObject.operation_attachment_id==attachmentData.operation_attachment_id){

                objArray[i]=attachmentData;
            }
        }
    }

}
/**
* finalcheck 
* do a final check for attachment before final submit
*/
Attachment.prototype.finalCheck=function(){
     var attachmentArr= new Array();
     for(i=0;i<objArray.length;i++){
         var attachmentObj= objArray[i];
         attachmentArr.push(attachmentObj.operation_attachment_name);
     }
     //alert(attachmentArr);
     results =checkArrDuplicate(attachmentArr);
     if(results.length!=0){
         alert("Attachment have some duplicate name \n"+results+"\nPlease remove it");
         return false;
     }
     
     // i think its not required to do this test
     //Its required now
     //alert(this.operation_id);
     //alert(this.db_index);
     //return false;
	 if(this.operation_id!=''){
    var status=xajax_checkAttachmentUniqueness(this.db_index,this.operation_id,$.toJSON(objArray));
    //alert(status);
    if(status!='go' && typeof(status)!='undefined'  ){
        alert("Adding attachment "+status+" will result in duplicate attachment.\n please remove it before submit");
        return false;
    }    
	 }
    return true; 
}


/**
*  function processDataTemp
*  @param object attachmentData data(of attachment)
*  use in add function in edit mode
*/
/*Attachment.prototype.processDataTemp=function(attachmentData){


    var arrayObject;
    for(i=0;i<objArray.length;i++){
        arrayObject=objArray[i];
        //alert(arrayObject.operation_attachment_id);
        if(arrayObject.operation_attachment_name==attachmentData.operation_attachment_name){

            objArray[i]=attachmentData;
        }
    }

}*/
Attachment.prototype.showHideIssueExpiry=function(attachmentId){
    
   // alert($("input[name='attachment_required_date"+attachmentId+"']:selected").val());
   if($("input[name='attachment_required_date"+attachmentId+"']:checked").val()==1){
       $('#expiry_after'+attachmentId+'').show();
   }else{
       $('#expiry_after'+attachmentId+'').hide();
       $("#expiry_id"+attachmentId).val("1");
   } 
}
/**
*  function deleteAttachment
*  @description :use to delete both new and actual attachment
*  
*/
Attachment.prototype.deleteAttachment=function(){
    try{
        if((selectedAttachment=='' )&& (selectedNewAttachment=='')){
            alert("Please select attachment to delete");
            return false;
        }
        //xajax_getJsonDataForAttachment(this.db_index,selectedAttachment,'delete');//prefetch data
        if(confirm("Are you sure you want to delete the selected attachments?")){
            var arrSelected=selectedAttachment.split(",");
            //var arrSelectedNew=selectedNewAttachment.split(",");
            var attachmentJsonObj;

            //@todo Need Replacement with for in
            for(i=0;i<objArray.length;i++){
                var attachmentObj= objArray[i];
                //alert(activeAttachments+' - '+attachmentObj.operation_attachment_id+'------- '+jQuery.inArray(attachmentObj.operation_attachment_id, activeAttachments));
                if((jQuery.inArray(attachmentObj.operation_attachment_id, arrSelected)!=-1) && (jQuery.inArray(attachmentObj.operation_attachment_id, activeAttachments)==-1)){
                    //change attachment name to deleted attachment to help us to find 
                    attachmentObj.operation_attachment_name='Deleted Attachment';
                    // alert(attachmentObj);
                    objArray[i]= attachmentObj;
                    
                    
                }   
				
				if((jQuery.inArray(attachmentObj.operation_attachment_id, arrSelected)!=-1) && (jQuery.inArray(attachmentObj.operation_attachment_id, activeAttachments)!=-1)){
					alert("Cannot delete "+attachmentObj.operation_attachment_name+" attachment");
				}

            }
            var j = 0;
            while (j < objArray.length) {
                var attachmentObj= objArray[j];

                //if(jQuery.inArray(attachmentObj.operation_attachment_name, arrSelectedNew)!=-1){
                if(attachmentObj.operation_attachment_id>10000){
                    //alert(attachmentObj);
                    objArray.splice(j, 1);    //remove added attachment either from duplicate or through add button
                } else { 
                    j++; 
                }
            }
            var attachmentJson=$.toJSON(objArray); //json encode the whole object array
            $('#attachment_json').val(attachmentJson); //assign it to html element for postback

            $(".ui-selected",$("#operation_selectable")).each(function(){
                var liId=this.id.replace("attachment_","");
                
                if(jQuery.inArray(liId, activeAttachments)==-1){
                    $(this).remove();          //remove all selected item
                    $('.operation_'+this.id).remove();
                }
            } );

        }
    }catch(err){
        alert("An Error occured while processing,click to OK to see error");
        alert(err);
    }
}

/** 
*   @description:display expiry related fields     
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.showAttachmentFields=function(obj,attachmentId){

    if(obj.checked==true) {
        //alert('checked');
        //show expiry related fields
        $('.expiry_fields'+attachmentId+'').show(); 
    }else{
        //alert('unchecked');
        //hide expiry related fields
        $('.expiry_fields'+attachmentId+'').hide(); 
    }      

}

/** @description:display/hide user input related fields
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/
Attachment.prototype.showUserDefinedInputs=function(obj,attachmentId){

    if(obj.checked==true) {                
        //show  related fields
        $('.user_fields'+attachmentId+'').show(); 
    }else{                     
        //hide  related fields
        $('.user_fields'+attachmentId+'').hide(); 
    }      

}


/** @description:display/hide member related fields
*   @param object obj( html element  object )
*   @param string attachmentId(id of attachment)    
*/     
Attachment.prototype.showMemberType=function(obj,attachmentId){

    if(obj.checked==true) {                
        //show  related fields
        $('.member_fields'+attachmentId+'').show(); 
    }else{                
        //hide  related fields
        $('.member_fields'+attachmentId+'').hide(); 
        $("input[name='member_type"+attachmentId+"[]']:checked").each(function(i){
            this.checked=false;
        }       
        )   ;
    }      

}
/**
* description show inactive Attachment
*  param object objACtive of showActive checkbox
* 
*/
Attachment.prototype.showInactive=function(objActive){

    if(objActive.checked==true){
        $('.inactive-attachment').show(); 
    }else{
        $('.inactive-attachment').hide(); 
    }     

}

Attachment.prototype.reset=function(divId){
   /* $(':input','#'+divId)
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');*/ 
    $(':input:not(:button,:submit,:checkbox,:radio)','#'+divId).each(function(i){
        
            $(this).val('');
            
           // alert(this.name) ;
            
    });  
    $(':checkbox,:radio','#'+divId).each(function(i){
             if(this.id!='attachment_active' && this.name!='attachment_required_date'){
                 $(this).removeAttr('checked');
                // alert(this.name)
             }
            
    });  

}
/**
*  function checkAttachment
*  verfiy for uniqueness
*  assign value to short name
*  disable save button
*  use xajax in synchronous mode
*  @param objName  (of textbox attachment_name)
*/
Attachment.prototype.checkAttachment=function(objName){
    //var result=  xajax.call("checkDuplicate",{parameters:[this.db_index,this.operation_id,$(objName).val()],mode:'synchronous'});
	
    var attachmentIdPatt=/(\d)+$/i;
    var attachment_id=$(objName).attr("id").match(attachmentIdPatt);          
    var result= attachment_id!=null?xajax_checkDuplicate(this.db_index,this.operation_id,$(objName).val(),attachment_id[0]):xajax_checkDuplicate(this.db_index,this.operation_id,$(objName).val(),'');

    var replacePatt=/[^a-zA-Z0-9\-]+/gi;
	if(typeof(result)=='undefined'){
		result=false;
	}

    //alert(attachment_id);
    if(result){      //check for match in db
        //alert('Match');  
        $(objName).css("color",'red');     //change font color
        if(attachment_id!=null){       //if in edit mode attachment_id is not null
            $('#add_attachment_save'+attachment_id[0]+'').attr('disabled','disabled'); //disabled save button
            $('#attachment_short_name'+attachment_id[0]+'').val($(objName).val().replace(replacePatt,'')).css("color",'red'); //change shortname color and value
        }else{
            $('#add_attachment_save').attr('disabled','disabled');  //in add mode  disable save button
            $('#attachment_short_name').val($(objName).val().replace(replacePatt,'')).css("color",'red'); //assign value after filtering and color 
        }

    }else{     //if no match found
        $(objName).css("color",'black');
        if(attachment_id!=null){
            $('#add_attachment_save'+attachment_id[0]+'').attr('disabled','');
            $('#attachment_short_name'+attachment_id[0]+'').val($(objName).val().replace(replacePatt,'')).css("color",'black');
        }
        else{
            $('#add_attachment_save').attr('disabled','');
            $('#attachment_short_name').val($(objName).val().replace(replacePatt,'')).css("color",'black');
        }
    }



	
}

/**
* @class AttachmentData
* @description :use for json encoding
* @param string attachmentId
* @param string operationId
* 
*/

var AttachmentData=function(attachmentId,operation_id){
    this.operation_id=operation_id;
    this.operation_attachment_id= attachmentId;
    
    /*if(parseInt(attachmentId)>=10000){ //attachmentId above 10000 is assumed as temp attachment dynamically added
        this.operation_attachment_id='';
    }  */
    
    this.operation_attachment_name=$('#attachment_name'+attachmentId+'').val();
    this.operation_attachment_short_name=$('#attachment_short_name'+attachmentId+'').val();     
    this.operation_attachment_category=$('#attachment_category'+attachmentId+'').val();     
    this.operation_attachment_active=$('#attachment_active'+attachmentId+':checked').val()==null?0:1;    
    this.operation_attachment_base_month_required=$('#attachment_base_month'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_required_date_type=$("input[name='attachment_required_date"+attachmentId+"']:checked").val();     
    this.operation_attachment_expiry_period_id=$("#expiry_id"+attachmentId).val();     
    this.operation_attachment_grace_period_id=$('#grace_period'+attachmentId+'').val();
    this.operation_attachment_alert_starting=$('#alert_starting'+attachmentId+'').val();
    this.operation_attachment_check_currency=$('#currency_check'+attachmentId+':checked').val()==null?0:1;    
    //alert(this.operation_attachment_grace_period_id);
    //alert(this.operation_attachment_alert_starting);
    this.operation_attachment_email_primary_admin=$('#notify_primary_admin'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_email_member=$('#notify_member'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_part91=$('#check_part_91'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_part125=$('#check_part_125'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_part135=$('#check_part_135'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_medical_class=$('#medical_class_req'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_user_defined_input=$('#user_defined'+attachmentId+':checked').val()==null?0:1;;
    this.operation_attachment_input1=$('#input_check_1'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_input2=$('#input_check_2'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_input3=$('#input_check_3'+attachmentId+':checked').val()==null?0:1;
    this.operation_attachment_input1_label=$('#input_text_1'+attachmentId+'').val();
    this.operation_attachment_input2_label=$('#input_text_2'+attachmentId+'').val();
    this.operation_attachment_input3_label=$('#input_text_3'+attachmentId+'').val();
    this.operation_attachment_notes=$('#attachment_notes'+attachmentId+'').val();
    this.operation_attachment_expire=$('#attachment_expire'+attachmentId+'').val();
    this.operation_attachment_member_type_requirement=$('#member_type_req'+attachmentId+':checked').val()==null?0:1; 
    var memberType=''; 
    $("input[name='member_type"+attachmentId+"[]']:checked").each(function(i){
        memberType +=$(this).val()+',';   
    }       
    )   ;
    this.operation_attachment_member_type=memberType.substr(0,memberType.length-1);
    //encode to json for decoding on process page    
}

/**
*  function populateCategory
*  @param string attachmentId
*  @global string strCategory(define in operation/update.php page)
*  @description :function bind category to attachment category textbox  
* 
*/
var populateCategory =function(attachmentId){
     //alert(attachmentId+'----'+strCategory);
    //var arrCategory   = new Array();
    // arrCategory=strCategory.split(",")
    $('#attachment_category'+attachmentId+'').autocomplete(strCategory);
} 

/**
* member attachment class used in member ERK module
* @param mixed operation_id
* @param mixed member_id
*/
var MemberAttachment=function(operationId,memberId,memberAttachmentId){
    this.member_attachment_id=typeof(memberAttachmentId)!='undefined'?memberAttachmentId:"";
    this.operation_id=operationId;
    this.member_id= memberId;
    // alert(operationAttachmentId);
    if(operationAttachmentId==''){
        this.operation_attachment_id=$('#operation_attachment').val();
    }else{
        this.operation_attachment_id=operationAttachmentId;  
    }
    //alert(this.operation_attachment_id);
    if($('#actual_issue_date').val()==''){
       $('#actual_issue_date').val('0000-00-00'); 
    } 
    this.member_attachment_issued_date= $('#actual_issue_date').val();
    if($('#expiry_period').val()!='0' && $('#expiry_period').val()!='' && $('#actual_issue_date').val()!='' && $('#actual_issue_date').val()!='0000-00-00'){
       var todaysDate=Date.parseExact($('#actual_issue_date').val(),"yyyy-MM-dd");
       //alert(todaysDate);
       var daysPeriod=$('#expiry_period').val(); 
       //daysPeriod=daysPeriod-1;
       todaysDate.add({ days: daysPeriod });
       //alert(daysPeriod);
       //alert(todaysDate);
       
       this.member_attachment_expired=todaysDate.toString("yyyy-MM-dd");
       //this.member_attachment_expired=$('#actual_expire_date').val();
    }else{
    //@todo add expiry period when expiry date type is set
     if($('#actual_expire_date').val()==''){
       $('#actual_expire_date').val('0000-00-00');
    } 
    this.member_attachment_expired=$('#actual_expire_date').val();
    }

    this.month_id=typeof($('#base_month').val())!='undefined'?$('#base_month').val():"";
    this.member_attachment_input1= typeof($('#member_attachment_input1').val())!='undefined'?$('#member_attachment_input1').val():"";
    this.member_attachment_input2= typeof($('#member_attachment_input2').val())!='undefined'?$('#member_attachment_input2').val():"";
    this.member_attachment_input3= typeof($('#member_attachment_input3').val())!='undefined'?$('#member_attachment_input3').val():"";
    this.medical_class_id= typeof($('#medical_class').val())!='undefined'?$('#medical_class').val():"";
    if(isImageUploaded){
        this.member_attachment_image= '';
        this.member_attachment_preview_png= '';
    }
    this.member_attachment_file_type= isImageUploaded;//currently will hold image load status,this we will later change to file type from php
    this.member_attachment_active='1';
    //isImageUploaded=0; //reset image/file uploaded status



}
/**
* postMemberAttachmentForm
* submit form
* @param mixed operation_id
* @param mixed member_id 
* 
*/
function postMemberAttachmentForm(operationId,memberId,memberAttachmentId){

    var objMemberAttachment=new MemberAttachment(operationId,memberId,memberAttachmentId); //create object

    var strMemberAttachmentJson=$.toJSON(objMemberAttachment);//convert to json
    //alert(strMemberAttachmentJson);
    $('#member_attachment_json').val(strMemberAttachmentJson);//assing to field
    // alert($('#member_attachment_json').val());
    if($('#issue_type').val()==1){
        if($('#actual_issue_date').val()==''){
            alert ("Please Enter Date");
            return false;

        }
    }else{
        if($('#actual_expire_date').val()==''){
            alert ("Please Enter Date");
            return false;

        }

    }
   // alert(editMode);
    if(isImageUploaded==0 && editMode==0){
        //alert("Please upload attachment");
        //return false;
    }    
    //document.update_member.submit();
    //save member attachment   
    saveMemberErkAttachment(0);



}
/**
*  Use for loading & saving Member Erk content after loading
*/
function saveMemberErkAttachment(loadData){
var thumbstatus=$('#show_thumb').attr('checked');
    if(loadData){ 
        $.ajax({     
            url: window['domain-url']+'&loadcontent=1',
            success: function(data) {
				try{      
                //$('#erkDiv').html(data); 
                 //$('#erkDiv').html('<img src="images/loading.gif" border="0">');
                document.getElementById('erkDiv').innerHTML=data; 
                $('#erkDiv').dateFormator(DateFormat);
                 if(thumbstatus){
                    //alert(thumbstatus);
                    $('#show_thumb').attr('checked','true');
                }
                showThumbnail();
                
                //addToolTipByClass();
                 //addShowHideFunction()
                 setTimeout("addShowHideFunction()",2000);
                 setTimeout("mainPositionSetter()",200);
                 //mainPositionSetter();
                //alert('Load was performed.');
				}catch(err){    
				}
            }

        });
    }else{

        $.ajax({
            url: window['domain-url']+'&savecontent=1&member_attachment_json='+$('#member_attachment_json').val(),
            success: function(data) {
               
				if(data==''){
                alert('Electronic Record Saved');
               
				}else{
					 alert(data);
				}
                saveMemberErkAttachment(1) ;
            }

        });

    }
}
/**
* function cancelMemberAttachmentForm
* @param string  operationId
* @param string  member_id
* @param string  db_index
* delete any temp image uploaded by users
*/
function cancelMemberAttachmentForm(operationId,member_id,db_index){

    var attachmentId=$('#operation_attachment').val();
    $('#member_attachment_json').val('');//assing to field
    if(isImageUploaded) { //check if any image/file uploaded by user if yes delete it on cancel
        $.ajax({
            type: "POST",
            url: "xajaxUtils/attachmentImage.php",
            data: "mode=tempDelete&operation_id="+operationId+"&member_id="+member_id+"&db_index="+db_index+"&attachment_id="+attachmentId+"" ,
            success: function(msg){
                // alert(msg);//debugging
                if(msg=='Error Deleting Image'){
                    alert(msg);
                }
            }
        });
    }
    $('#attachment_div').html('');
    operationAttachmentId='';
    mainPositionSetter();

}
/**
*   setAttachmentView after show inactive checkbox clicked
*/
function setAttachmentView(){
    //  return "true";
    var obj=document.getElementById('show_inactive_attachment');
    // $('.table_state span').remove(); 
    $('.table_state').each(function(i){
        if(obj.checked==true){

            $("tr.attachment_state",$(this)).css("display","block");
            xajax_setSession('attachment_inactive',1);  
        }else{
            $("tr.attachment_state",$(this)).css("display","none");
            xajax_setSession('attachment_inactive',0);    
        }
        var cnt=0;
        $(this).show(); 
        $("tr.attachment_state",$(this)).each(function(i){
            if( $(this).is(':hidden') ) {
                cnt++;  
            }
        })
        //alert(cnt);
        //alert($(".attachmentDiv tr",$(this)).size());
        if(cnt==$("div:first tr",$(this)).size()){
            $(this).hide();
        }else{
            $(this).show(); 
        }


    } )


    addShowHideFunction(); 
    mainPositionSetter();
}
/**
*  for show hide arrow
*/

function addShowHideFunction(){

  
    $("span:[id^='arrow']").remove();
    $('.table_state').each(function(i){

        var pos=$(this).position();
        var obj=$(this);
        $("body").append("<span id='arrow"+i+"' style='position:absolute'><img src='images/arrowdown.gif' title='collapse'></span>");
        $('#arrow'+i+'').css({"left": pos.left-8,"top":parseFloat(pos.top+13)});
        
        $('#arrow'+i+' img').click(function(){
            //alert(this.src)
            if(this.title=='collapse'){
                this.src="images/arrowright.gif";
                this.title='expand' ;
                //alert(obj.find(".attachmentDiv").html());
                obj.find(".attachmentDiv").css("display","none")
                //alert(obj.find(".attachmentDiv").css("display"));
                obj.find(".sorting").hide();
                obj.find(".expiry").show();
                obj.find(".warning").show();
                positionSetter();
                mainPositionSetter();
            }else{
                this.src="images/arrowdown.gif"; 
                this.title='collapse';

                obj.find(".attachmentDiv").css("display","block")
                obj.find(".sorting").show();
                obj.find(".expiry").hide();
                obj.find(".warning").hide();
                positionSetter();
                mainPositionSetter();
            }

        })


    });



}
/**
* for setting position of arrow
*/
function positionSetter(){
    //alert("Hello");
    $('.table_state').each(function(i){

        var pos=$(this).position();      
        $('#arrow'+i+'').css({"left": pos.left-8,"top":parseFloat(pos.top+13)});
    }); 
}

function collapseAll(){
    //  alert("hi");
    $('.table_state').each(function(i){

        var pos=$(this).position();
        var obj=$(this);
        //$("body").append("<span id='arrow"+i+"' style='position:absolute'><img src='images/arrowdown.gif' title='collapse'></span>");
        $('#arrow'+i+'').css({"left": pos.left-8,"top":parseFloat(pos.top+13)});

        $('#arrow'+i+' img').attr("src","images/arrowright.gif");
        $('#arrow'+i+' img').attr("title","expand");         //alert(this.src)


        obj.find(".attachmentDiv").css("display","none");
        obj.find(".sorting").hide();
        obj.find(".expiry").show();
        obj.find(".warning").show();
        positionSetter();
        mainPositionSetter();




    });




}

function expandAll(){
    $('.table_state').each(function(i){

        var pos=$(this).position();
        var obj=$(this);
        // $("body").append("<span id='arrow"+i+"' style='position:absolute'><img src='images/arrowdown.gif' title='collapse'></span>");
        $('#arrow'+i+'').css({"left": pos.left-8,"top":parseFloat(pos.top+13)});
        // alert('#arrow'+i+' img');
        $('#arrow'+i+' img').attr("src","images/arrowdown.gif");
        $('#arrow'+i+' img').attr("title","collapse");         //alert(this.src)


        obj.find(".attachmentDiv").css("display","block");
        obj.find(".sorting").show();
        obj.find(".expiry").hide();
        obj.find(".warning").hide();
        positionSetter();
        mainPositionSetter();

    });

}
var loadCheck=0;
/**
* add display arrow to main block of the page
*/
function addShowHideMainFunction(){
    //$("span:[id='mainspan']").remove(); 
    $('.titleAlert').each(function(i){

        var pos=$(this).offset();
        var obj=$(this);
        $("body").append("<span id='mainspan"+i+"' style='position:absolute'><img src='images/arrowdown.gif' title='collapse'></span>");
        $('#mainspan'+i+'').css({"left": pos.left-30,"top":parseFloat(pos.top+2)});
        
        $('#mainspan'+i+' img').click(function(){
            //alert(this.src)
            if(this.title=='collapse'){
                this.src="images/arrowright.gif";
                this.title='expand' ;
                obj.next(".cSquare,.Square").hide();
                //alert(obj.find(".table_state"));
                if(typeof( obj.find(".table_state").attr("name"))!="undefined"){
                    alert(obj.find(".table_state").attr("name"));
                    $("span[id^='arrow']").hide();
                }
                mainPositionSetter();
            }else{
                this.src="images/arrowdown.gif"; 
                this.title='collapse';
                obj.next(".cSquare,.Square").show();
                // alert(obj.find(".table_state"));
               if(typeof( obj.find(".table_state").attr("name"))!="undefined"){
                    $("span[id^='arrow']").show();
                }
                //obj.find(".cSquare").show(); 

                mainPositionSetter();
            }

        })
          if(obj.next(".attachment_hide").attr("id")=='hideThis'){
            
            $('#mainspan'+i+' img').trigger("click")
            // obj.next(".attachment_hide").hide();
            setTimeout("mainPositionSetter()",3000);
        }

    });



}

function delayTimeout(){
    setTimeout("mainPositionSetter()",2000);
}

/**
* for setting position of main arrow
*/
function mainPositionSetter(){
   //alert("hi");
    $('.titleAlert').each(function(i){

        var pos=$(this).offset();      
        $('#mainspan'+i+'').css({"left": pos.left-30,"top":parseFloat(pos.top+2)});
    }); 
   setTimeout("positionSetter()",2000);
}


//date parser plugin
//@author pavan sharma
(function($){

    //Attach this new method to jQuery
    $.fn.extend({ 

        //This is where you write your plugin's name
        dateFormator: function(dateformat) {

            //Iterate over the current set of matched elements
            return this.each(function() {
                var result='';
                var newresult='';
                var dt='';
                //pattern to be match here
                var patt=/(\d{4}-\d{2}-\d{2})\b/gm;                 
                var str=$(this).html();
                //newresult=str;
                result=str.match(patt);
                if(result!=null){
                    if(result.length==1){
						try{
                        dt=Date.parseExact(result,"yyyy-MM-dd");                  
                        str=str.replace(eval('/'+result+'/gi'),dt.print(dateformat)); 
						}catch(err){
						}
                    }else{
                        for(i=0;i<result.length;i++){
                            dt=Date.parseExact(result[i],"yyyy-MM-dd");
                            // alert(result[i]+'----'+dt.print(dateformat));

                            str= str.replace(eval('/'+result[i]+'/gi'),dt.print(dateformat)); 
                        }
                    }
                }
                //alert(str);
                $(this).html(str);
            }); 
        }
    });

    //pass jQuery to the function, 
    //So that we will able to use any valid Javascript variable name 
    //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )        
})(jQuery);

//for showing popup
(function($){           
    $.fn.popupWindow = function(instanceSettings){

        return this.each(function(){

            $(this).click(function(){

                $.fn.popupWindow.defaultSettings = {
                    centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
                    centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
                    height:500, // sets the height in pixels of the window.
                    left:0, // left position when the window appears.
                    location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
                    menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
                    resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
                    scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
                    status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
                    width:500, // sets the width in pixels of the window.
                    windowName:null, // name of window set from the name attribute of the element that invokes the click
                    windowURL:null, // url used for the popup
                    top:0, // top position when the window appears.
                    toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
                };

                settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
                 if(typeof(settings.callBack)=='function'){
                      //alert(settings.callBack());
                      //alert("hi");
                        settings.windowURL = settings.callBack();
                        //alert(settings.windowURL);
                       
                 }
                var windowFeatures =    'height=' + settings.height +
                ',width=' + settings.width +
                ',toolbar=' + settings.toolbar +
                ',scrollbars=' + settings.scrollbars +
                ',status=' + settings.status + 
                ',resizable=' + settings.resizable +
                ',location=' + settings.location +
                ',menuBar=' + settings.menubar;

                settings.windowName = this.name || settings.windowName;
                settings.windowURL = settings.windowURL || this.href || this.src;
                var centeredY,centeredX;

                if(settings.centerBrowser){

                    if ($.browser.msie) {//hacked together for IE browsers
                        centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
                        centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
                    }else{
                        centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
                        centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
                    }
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
                }else if(settings.centerScreen){
                    centeredY = (screen.height - settings.height)/2;
                    centeredX = (screen.width - settings.width)/2;
                    //alert(settings.windowURL);
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
                }else{
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();    
                }
                return false;
            });

        });    
    };
})(jQuery);

/**
* bindImagePopup
* use for window popup on attachment image click
* @param imageId
*/
function bindImagePopUp(imageId){
    //pic1= new Image(); 
    //alert($('#'+imageId+' img').attr("rel"));
    //pic1.src=$('#'+imageId+' img').attr("rel");
      
    $('#'+imageId+'').popupWindow({ 
        centerScreen:1,
        //width:pic1.width,
        //height:pic1.height,
        windowURL:$('#'+imageId+' img').attr("rel"),
        windowName:'AttachmentPopUp',
        scrollbars:1 
    }); 

    setTimeout("mainPositionSetter()",1000);
}

function bindAttachmentCheck(objId){
     $('#'+objId).popupWindow({ 
        centerScreen:1,
        //width:pic1.width,
        //height:pic1.height,
        
        windowName:'AttachmentPopUp',        
        callBack:checkAttachmentMemberQuotes,
        scrollbars:1 
    }); 
}
/**
* handler function for making url for check function from quote page
*/
function checkAttachmentMemberQuotes(){
     // alert($('#leg_ids').val()); 
    var aPasValue=new Array();
    var aPilotValue=new Array();
    var aFasValue=new Array();
    var legValue=new Array();
    var outDate=new Array();
    var partCheck=new Array();
   
     aPasValue=$('#passengers').val().split(":");
     aPilotValue=$('#pilots').val().split(":");    
     aFasValue=$('#fas').val().split(":");
     legValue=$('#leg_ids').val().split(":");
     
     //alert(legValue);
     for(i=0;i<legValue.length;i++){
         
        outDate.push($('#out_date_'+legValue[i]).val());
        partCheck.push($('#segment_type_id_'+legValue[i]).val());
     }
     var dataLiteral='';          
     dataLiteral={'operation_id':$('#operation_id').val(),'dispatchId':$('#eid').val(),'passenger':aPasValue,'pilot':aPilotValue,'flightAttendant':aFasValue,'legs':legValue,'outDate':outDate,'partCheck':partCheck};
     var returnUrl='xajaxUtils/checkAttachment.php?dataLiteral='+$.toJSON(dataLiteral);
     //alert(returnUrl);
      return returnUrl;
    
    /*alert(aPasValue);
    alert(aPilotValue);
    alert(aFasValue);*/
    
}
/**
* Array unique function
*/
/*Array.prototype.unique =function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++) {
            // If this[i] is found later in the array
            if (this[i] === this[j])
                j = ++i;
        }
        a.push(this[i]);
    }
    return a;
};  */

function uniqueThis(strCategoryArr){
    
     var a = [];
    var l = strCategoryArr.length;
    for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++) {
            // If strCategoryArr[i] is found later in the array
            if (strCategoryArr[i] === strCategoryArr[j])
                j = ++i;
        }
        a.push(strCategoryArr[i]);
    }
    return a;
    
    
}

function randomNo(minVal,maxVal,floatVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

/*function checkArrDuplicate( A ) { // finds any duplicate array elements using the fewest possible comparison
    var i, j, n;
    n=A.length;
    // to ensure the fewest possible comparisons
    for (i=0; i<n; i++) {       // outer loop uses each item i at 0 through n
        for (j=i+1; j<n; j++) { // inner loop only compares items j at i+1 to n
            if (A[i]==A[j]) return true;
    }    }
    return false;
}   */

function checkArrDuplicate(arr){
    var sorted_arr = arr.sort(); // You can define the comparing function here. JS default uses a crappy string compare.
    var results = [];
    for (var i = 0; i < arr.length - 1; i += 1) {
        if(sorted_arr[i]!='Deleted Attachment') {
            if (sorted_arr[i + 1] == sorted_arr[i]) {
                results.push(sorted_arr[i]);
            }
        }
    }
    return results;
}

function assignValue(arg){
    //alert(arg);
    objArray.push($.evalJSON(arg)); //load ObjArray with initial javascript attachment object data 
}

 function classDivHeight(classN){
     $("."+classN+"").each(function(i){
        // alert($(this).height())  ;
     })
 }

//alert(randomNo(10001,65534));

