jQuery(document).ready( function() {
var j = jQuery;
/**
 *  TODO: Minimize dependency of Dom elements by Id, as much as possible
 */

/*********                     Helper Function for Gallery                                             ***/


//if the file element exists activate swf uploader
if(j("#file").get(0))//just to avoid the conflict
    swfuplod_init_for_media("file");

//see above line, activate swf upload for cover upload in case we are opening directly the cover upload page for gallery
if(j("#cover_file").get(0))
   swfuplod_init_for_gallery("cover_file");

//same as above two, required for activating sortable when the sorting page is directly opened
if(j("#gallery-sortable").get(0))
    j("#gallery-sortable").sortable({opacity: 0.6, cursor: 'move'});

//global variables,bad thing but required
gallery_upload_error=false;//handling upload errors
gallery_upload_error_message='';//in next version, we will use it as an array of errors


// Show notification using the jquery_notice Plugin
//will be dropping this, as we do not need this , we can  handle thing using dom notification
function notify(text,stay){
    if(stay==undefined)
        stay=false;//where to stay sticky or not
        jQuery.noticeAdd({
                        'text': text,
                        'stay': stay
                });
 }
 

// Hide update message, what about error handing bro
function hide_message(){
    j("#message").empty();
    j("#message").removeClass();
}

// Show Update Message, need some update as red:D for error handing, currently everything is green
function show_message(msg,error){
   if(error==undefined||!error)
   j("#message").addClass("updated").addClass("fade");
   else
       j("#message").addClass("error");

   j("#message").html("<p>"+msg+"</p>");

}

/*
 *--------------------------- File Upload functions for swf upload ------------------------------------*
 *-----------------------------------------------------------------------------------------------------*
 **/

/*************************************************************** SWF Upload Helper Functions *************************************/

/* Generic functions like queueing, handling queue error etc*/
// Handles Listing of files, just a UI function, It lists the file when file is selected in the DOM

function file_queued(event, file){
    var listitem='<li id="'+file.id+'" >'+
                    'File: <em>'+file.name+'</em> ('+Math.round(file.size/1024)+' KB) <span class="progressvalue" ></span>'+
                    '<div class="progressbar" ><div class="progress" ></div></div>'+
                    '<p class="status" >Pending</p>'+
                     '<span class="cancel" >&nbsp;</span>'+
                '</li>';
	j('#log').append(listitem);
	j('li#'+file.id+' .cancel').bind('click', function(){

        var swfu = j.swfupload.getInstance('#swfupload-control');
	swfu.cancelUpload(file.id);
	j('li#'+file.id).slideUp('fast');
			});

}

//Handle the uploading error, i.e basic client side error handing by swf
function file_queue_error( file, errorCode, message){
    notify('Size of the file '+file.name+' is greater than limit'+message,1);//notify the error to the user
}

//Update the Number of file selected etc when File dialog is complete/closed
 
function file_dialog_complete(event, numFilesSelected, numFilesQueued){
    j('#queuestatus').text('Files Selected: '+numFilesSelected+' / Queued Files: '+numFilesQueued);
}

// helper function, called when swfupload starts uploading
function upload_start(event, file){
    j('#log li#'+file.id).find('p.status').text('Uploading...');
    j('#log li#'+file.id).find('span.progressvalue').text('0%');
    j('#log li#'+file.id).find('span.cancel').hide();
    j(".guploading").show();//show the progress icon

}
//Helper function to handle the upload progress and show user the progress

function upload_progress(event, file, bytesLoaded){
    //Show Progress
    var percentage=Math.round((bytesLoaded/file.size)*100);
    j('#log li#'+file.id).find('div.progress').css('width', percentage+'%');
    j('#log li#'+file.id).find('span.progressvalue').text(percentage+'%');
}



/**
 * @desc helper function used to remove file from the list of selectd files on error/success
 */
function remove_file_from_list(file){
      var item=j('#log li#'+file.id);
          item.find('div.progress').css('width', '100%');
          item.find('span.progressvalue').text('100%');
	  item.addClass('success').find('p.status').html('Done!!!');
	  j(item).remove();//remove the file listing from dom
}


/**
 * Helper function for gallery cover upload complete
 * *
 */
function gallery_upload_complete(event, file){
    var swfu = j.swfupload.getInstance('#swfupload-control');
    j('li#'+file.id).slideUp('fast');
    j(".guploading").hide();
}
/**
 * @desc  Helper functuion, used when a gallery save is clicked and response is recieved from server
 */
function gallery_upload_success(event, file, serverData){
    //alert(serverData)
    var resp=JSON.parse( serverData);
      if(resp.data)
           show_message(resp.data.msg);// show update
      else
         show_message(resp.error.msg,1);

      remove_file_from_list(file);
}





//For Media
//Helper function for swfupload, called when a file upload is complete

function media_upload_complete(event, file){
    var swfu = j.swfupload.getInstance('#swfupload-control');
    j('li#'+file.id).slideUp('fast');
            // upload has completed, try the next one in the queue
    var stats=swfu.getStats();
    if(stats.files_queued!=0)
      j(this).swfupload('startUpload');
    else{
        j(".guploading").hide();//show the progress icon
         //simulate a click on the other tab
         //check for upload errors , if none
         if(!gallery_upload_error)
            j("#gallery-media-edit").click();//simulate click, let us see
         else {
                show_message(gallery_upload_error_message,1);
                 //reset error message
                 gallery_upload_error_message='';
                 gallery_upload_error=false;
             }
      }
}

//Helper function, used when a media is uploaded and saved
function media_upload_success(event, file, serverData){
    //alert(serverData);
    //alert(serverData);
    resp=JSON.parse(serverData);
    if(resp.data)
         j("#update_media_upload").prepend(build_media_html(resp.data));
    else
        {notify(resp.error.msg,1);//notify the error
        gallery_upload_error=true;
        gallery_upload_error_message=resp.error.msg;
        }
    remove_file_from_list(file);
}

function activity_upload_success(event, file, response){
    //alert(serverData);
   //it should be simply activity update function
    var form=j("#whats-new-form");
    j( 'form#' + form.attr('id') + ' span.ajax-loader' ).hide();
      /* Check for errors and append if found. */
	if ( response[0] + response[1] == '-1' ) {
		form.prepend( response.substr( 2, response.length ) );
		jq( 'form#' + form.attr('id') + ' div.error').hide().fadeIn( 200 );
		button.attr("disabled", '');
            } else {
                	if ( 0 == j("ul.activity-list").length ) {
			j("div.error").slideUp(100).remove();
			j("div#message").slideUp(100).remove();
			j("div.activity").append( '<ul id="activity-stream" class="activity-list item-list">' );
			}

		j("ul.activity-list").prepend(response);
		j("ul.activity-list li:first").addClass('new-update');
		j("li.new-update").hide().slideDown( 300 );
		j("li.new-update").removeClass( 'new-update' );
		j("textarea#whats-new").val('');
        	}
		

    
    remove_file_from_list(file);
    //hide the form
    j("#whats-new-options form").remove();
}

function activity_upload_complete(event, file){
   // alert("yes yes");
    var swfu = j.swfupload.getInstance('#swfupload-control');
    j('li#'+file.id).slideUp('fast');
            // upload has completed, try the next one in the queue
   j(".guploading").hide();//show the progress icon
       
    if(!gallery_upload_error){
            j("#gallery-media-edit").click();//simulate click, let us see
    }
    else {
                show_message(gallery_upload_error_message,1);
                 //reset error message
                 gallery_upload_error_message='';
                 gallery_upload_error=false;
             }
     
}



/**
 * @desc Populate parameters for media upload
 * */
function populate_post_params_for_media(){
  var swfu = j.swfupload.getInstance('#swfupload-control');
    swfu.addPostParam("action","save_gallery_media_bulk");
    swfu.addPostParam("cookie",encodeURIComponent(document.cookie));
    swfu.addPostParam("user-galleries",j("#gallery_media_upload_form #galleries-list").val());
    swfu.addPostParam("_wpnonce",j("input#_wpnonce-save-gallery-image").val());
    swfu.addPostParam("component_type",cur_component);
    swfu.addPostParam("component_id",cur_component_id);
}


function populate_post_params_for_activity(){
  var swfu = j.swfupload.getInstance('#swfupload-control');
    swfu.addPostParam("action","upload_from_activity");
    swfu.addPostParam("cookie",encodeURIComponent(document.cookie));
    swfu.addPostParam("user-galleries",j("#gallery_media_upload_form #galleries-list").val());
    swfu.addPostParam("_wpnonce",j("input#_wpnonce-save-gallery-image").val());
    swfu.addPostParam("component_type",cur_component);
    swfu.addPostParam("component_id",cur_component_id);
}
/**
 * @desc Initialize swfuploader on an element
 */
function swfuplod_init(id){
    gallery_upload_settings.button_placeholder_id=id;
    guploader=j('#swfupload-control').swfupload(gallery_upload_settings);//instantiate
    guploader.bind("fileQueued",file_queued);
    guploader.bind("fileQueueError",file_queue_error);
    guploader.bind("fileDialogComplete",file_dialog_complete);
    guploader.bind("uploadStart",upload_start);
    guploader.bind("uploadProgress",upload_progress);

}

function  swfuplod_init_for_gallery(id){
     swfuplod_init(id);
     guploader.bind("uploadComplete",gallery_upload_complete);
     guploader.bind("uploadSuccess", gallery_upload_success);//associate a upload success handler function
}


function  swfuplod_init_for_media(id){
    swfuplod_init(id);
    guploader.bind("uploadComplete",media_upload_complete);
    guploader.bind("uploadSuccess", media_upload_success);
}

function  swfuplod_init_for_activity(id){

   // gallery_upload_settings.file_upload_limit=2;
    gallery_upload_settings.file_upload_limit=1;
    swfuplod_init(id);
     //var swfu = j.swfupload.getInstance('#swfupload-control');
    guploader.unbind("fileQueueError",file_queue_error);
    guploader.bind("fileQueueError",function(){
            notify("Please cancel the queued media to select new",1);
            });

    guploader.bind("uploadComplete",activity_upload_complete);
    guploader.bind("uploadSuccess", activity_upload_success);
}








/**
 *----------------------------------- Basic helper Functions for gallery ---------------------------------------------*
 *--------------------------------------------------------------------------------------------------------------------*
 */

/*** general Helper functions for gallery  ***********/
/**
 *  get id from from the dom elemnts
 *  e.g <div id="name_something_32"> will return 32
 */
function get_id(el){
    var eid=el.id;
    var beg=eid.lastIndexOf('_');//dom id is somename_something_idofgallery/media
    var id=eid.slice(beg+1);
    return id;
    
}

/**
 * @desc Get a query variable's value from the url
 * url must be of the form http://example.com/abc/xyz/?name=val&name1=val2..
 */
 
function get_var_in_url(url,name){
    var urla=url.split("?");
    var qvars=urla[1].split("&");//so we hav an arry of name=val,name=val
    for(var i=0;i<qvars.length;i++){
        var qv=qvars[i].split("=");
        if(qv[0]==name)
            return qv[1];
      }
}
/**
 * @desc Get the nonce from the url, the nonce must be of style _wpnonce=hdfdh465675,i.e. the name as _wpnonce
 */
function get_nonce(url){
    return get_var_in_url(url,"_wpnonce");
}
/**
 * @desc Hide and show the Dom Elements
 */
function hide_and_show(el,html){
    j(el).hide('slow',function(){
         j(el).empty();
        });
     j(el).show('slow',function(){
            j(el).html(html);
     } );
}


 /**
  * @desc Build Media HTML for gallery
  */
 function build_media_html(media){
 var html="<div class='media'><h3>"+media.title+"</h3>\n";
     html+=media.thumb;//we have the linked image
     html+="</div>";
  return html;
 }
/**
 * @desc delete gallery, remove from dom
 */
function delete_gallery(gallery_id){
   //remove the gallery from parent
   var gdiv="gallery_"+gallery_id;
   j("#"+gdiv).remove();
}

/**
 * @desc make the media editable inline
 */
function make_media_editable(media,type){
    j(".media-content",media).hide();
    j("form",media).show();
    return false;
}

/**
 * @desc delete media from dom
 */
function delete_media(id){
var media_div="#gallery_media_"+id;
    j(media_div).remove();
}
/**
 * @desc Update the dom element for media
*/
function replace_media(media,mdiv){
   j(".media-title",mdiv).html(media.title);
   j(".media-description",mdiv).html(media.description);
   j("form",mdiv).hide();
   j(".media-content",mdiv).show('fast');
   notify(media.msg);
}


/**** end of helper functions for swf upload ****/



/*------------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------------*/

/**
 * This section deals with gallery creation,
 * Gallery Editing
 * Gallery Deletion and so
 *
 */

/**
 *@desc Load Gallery Creation form via ajax
 */

j("#gallery_create,#add_new_gallery_link").live('click',
    function() {
        var url = j(this).attr('href');//get the url
        j.post( ajaxurl, {
                action: 'show_gallery_create_form',
                'cookie': encodeURIComponent(document.cookie),
                'component':cur_component,
                'component_id':cur_component_id,
		'_wpnonce': get_nonce(url)
                },
		function(response){
                    j("#galleries").fadeOut(200,
                	function() {
			    j("#galleries").html(response);
                            j("#galleries").fadeIn(200);
                            j.scrollTo( j('form#gallery_create_form input #gallery_save'), 500, {offset:+280, easing:'easeout'} );
                            }
                        );
		});
		
	return false;
});

/**
 * @desc Process gallery creation, Save the gallery data to database
 */
j("#gallery_save").live('click',
	function() {
            //disable the create button and text fields
            var button = j(this);
            var form = j("form#gallery_create_form");  //button.parent().parent().parent().parent();

		j("input,textarea",form).each( function() {
                    if ( j.nodeName(this, "textarea") || j.nodeName(this, "input") )
				j(this).attr( 'disabled', 'disabled' ); 
		});

		j( 'form#' + form.attr('id') + ' span.ajax-loader' ).show();
            j.post(ajaxurl, {
                action: 'gallery_create_save',
                "cookie": encodeURIComponent(document.cookie),
                "gallery_title":j("#gallery_create_form #title").val(),
                "gallery_status":j("#gallery_create_form #gallery_status").val(),
                "gallery_description":j("#gallery_create_form #gallery_description").val(),
                "gallery_type":j("#gallery_create_form #gallery_type").val(),
                "component":cur_component,
                "component_id":cur_component_id,
		"_wpnonce":j("#gallery_create_form input#_wpnonce-gallery_create_save").val()

			},
          function (response){
              //parse the response
              resp=JSON.parse(response);
              j( 'form#' + form.attr('id') + ' span.ajax-loader' ).hide();

			j("input,textarea",form).each( function() {
                    if ( j.nodeName(this, "textarea") || j.nodeName(this, "input") )
				j(this).attr( 'disabled', '' );
                            });
                        button.attr("disabled", '');
                
              if(resp.error!=undefined)
                  notify(resp.error.msg,1);
              else{
                  //redirect to the upload page
                  var gallery=resp.data;
                 //bring the upload form 
                 //redirect page to upload image
                 window.location.replace(gallery.add_media_link);
               }
             }

        );

  return false;

});


/***
 * For Single Gallery editing
 * */
j("#gallery_gallery_edit,.gallery-actions a.edit").live('click',function(){
    //if edit link was clicked,
    var url = j(this).attr('href');
    var gid=get_var_in_url(url,'gallery_id');
    var nonce = get_nonce(url);
    j.post(ajaxurl,{
                 action:"single_gallery_edit",
                 cookie:encodeURIComponent(document.cookie),
                 'gallery_id':gid,
                 '_wpnonce':nonce
                  },
                function(response){
                j("#galleries").fadeOut(200,
		 function() {
			
			j("#galleries").html(response);//do not prepend just remove the all other things
                        j("#galleries").fadeIn(200);
                        j.scrollTo( j('.gallery-cover'), 500, {offset:-40, easing:'easeout'} );
			}
		);
                    
             });
return false;
});



/**
 * @desc Load the Media Upload form*/
j(".gallery-actions a.upload, #upload_media_link,#gallery_media_upload").live('click',
    function() {
        var url = j(this).attr('href');
        var gid=get_var_in_url(url,'gallery_id');
	var nonce = get_nonce(url);
	j.post( ajaxurl, {
                            action: 'show_gallery_media_upload_form',
			    'cookie': encodeURIComponent(document.cookie),
                            'gallery_id':gid,
                            '_wpnonce': nonce
			},
		function(response){
                       var p="#galleries";
			j(p).fadeOut(200,
                            function() {
                                j(p).html(response);//do not prepend just remove the all other things
                                swfuplod_init_for_media("file");
				j(p).fadeIn(200);
                                j.scrollTo( j('form#gallery_media_upload_form'), 500, {offset:-50, easing:'easeout'} );
                	 }
			);
				
		});
		
	return false;
});
/*** dropped for stable******/
//a;llow uploading from activity

j("#gallery_upload_buttons_for_activity a").live('click',
    function() {
        var el=j(this);
        j("#gallery_media_upload_form").remove();
        var type=j(this).attr("id");//use id as type detector , may be photo/audio/video
       
	j.post( ajaxurl, {
                            action: 'show_gallery_media_upload_form_activity',
			    'cookie': encodeURIComponent(document.cookie),
                            'gallery_type':type,
                            
                            '_wpnonce': "nonce"
			},
		function(response){
                       var container=j(el).parent().parent();//whats new options
                       j(container).fadeOut(200,
                            function() {
                                j(container).append(response);//do not prepend just remove the all other things
                                swfuplod_init_for_activity("file");
				j(container).fadeIn(200);
                                j.scrollTo( j('form#gallery_media_upload_form'), 500, {offset:-50, easing:'easeout'} );
                	 }
			);

		});

	return false;
});

/**
 *For Single Gallery Media editing**/

j("#gallery-media-edit").live("click",function(){
    
    var url = j(this).attr('href');
    var gid=get_var_in_url(url,'gallery_id');
    var nonce = get_nonce(url);
    j.post( ajaxurl, {
		action: 'show_media_edit_form',
		'cookie': encodeURIComponent(document.cookie),
                'gallery_id':gid,
		'_wpnonce': nonce
		},
	   function(response){
                var p="#galleries";
		j(p).fadeOut(200,
		      function() {
                        j(p).html(response);//do not prepend just remove the all other things
                        j(p).fadeIn(200);
                        j.scrollTo( j(p), 500, {offset:-50, easing:'easeout'} );
			}
		    );
       });
    
    return false;
});

/**
 *For Drag and Drop Media Reordering
 */
j("#gallery_media_organize").live('click',function(){
 var url = j(this).attr('href');
 var gid=get_var_in_url(url,'gallery_id');
 var nonce = get_nonce(url);
 j.post( ajaxurl, {
	action: 'show_media_reorder_form',
	'cookie': encodeURIComponent(document.cookie),
        'gallery_id':gid,
	'_wpnonce': nonce
	},
     function(response){
           var p="#galleries";
	   j(p).fadeOut(200,
	     function() {
		j(p).html(response);//do not prepend just remove the all other things
                j(p).fadeIn(200);
                j.scrollTo( j(p), 500, {offset:-50, easing:'easeout'} );
                j("#gallery-sortable").sortable({opacity: 0.6, cursor: 'move'});
	    }
	);
    });
return false;
});

/***** For  The reordering of media inside a gallery*/

j("#gallery_media_rorder_form input[type='submit']").live('click',function(){
   hide_message();
   var nonce=j("input#_wpnonce-gallery_media_reorder").val();
   var gallery_id=j("input#reorder_gallery_id").val();
   var data=j("#gallery-sortable").sortable("serialize")+"&_wpnonce="+nonce+"&gallery_id="+gallery_id+"&action=reorder_gallery_media&cookie="+ encodeURIComponent(document.cookie);
   j.post( ajaxurl, data,
            function(response){
                resp=JSON.parse(response);
                if(resp.error!=undefined)
                         show_message(resp.error.msg,1);
                 else
                     show_message(resp.msg,0);

	      });
  
    return false;
});

/**
 * @desc Delete gallery using ajax
 */
 j(".gallery-actions a.delete,#gallery_gallery_delete").live('click',
        function() {
	    var url = j(this).attr('href');
            var gid=get_var_in_url(url,'gallery_id');
	    var nonce = get_nonce(url);
            if(confirm("Are You sure. You will loose all the media/comments")){
		j.post( ajaxurl, {
			action: 'delete_gallery',
			'cookie': encodeURIComponent(document.cookie),
                        'gallery_id':gid,
			'_wpnonce': nonce
			},
		   function(response){
                      response=JSON.parse(response);
                      delete_gallery(response.data.id);
                      notify(response.data.msg);
                      window.location.replace(gallery_home_url);//send user back to gallery home
			});
            }
			return false;
    }
);

/**
 * @desc Save gallery data inline On Single gallery editing Page
 **/

j("form#gallery_edit_info input[type='submit']").live("click",function(){
   hide_message();//hide any message shown earlier
   var gallery_edit_form=j("form#gallery_edit_info");
   var gdiv=j(".edit-gallery",gallery_edit_form).get(0);//the gallery div
   var id=get_id(gdiv);//get the id of this gallery /the actual content of gallery

 j.post( ajaxurl, {
		'action': 'inline_update_gallery',
                'gallery_id':id,
		'cookie': encodeURIComponent(document.cookie),
                'gallery_title':j("#gallery_title",gdiv).val(),
                'gallery_status':j("#gallery_status",gdiv).val(),
                'gallery_description':j("#gallery_description",gdiv).val(),
		'_wpnonce':j("#_wpnonce-edit-save-gallery",gdiv).val()

			},
            function(response){
               response=JSON.parse(response);
               if(response.error!=undefined){
                  show_message(response.error.msg,1);//error message should be shown
                  return false;
                }
                //if we are here..there were no error..so we can proceed
        	var gallery=response.data;
                show_message(gallery.msg,0);
         
	});
  return false;
});

j("#media_bulk_edit_form input[type='submit']").live('click',function(){
    var data=j("#media_bulk_edit_form").serialize();
    data+="&action=bulk_media_update&cookie="+encodeURIComponent(document.cookie);
    j.post( ajaxurl, data,
            function(response){
                response=JSON.parse(response);
                if(response.error!=undefined)
                    show_message(response.error.msg,1);
                else
                    show_message(response.msg,0);
	      });

 return false;
    
});
/** Save gallery Cover Image**/
j("#save_gallery_cover").live('click',function(){
     var swfu = j.swfupload.getInstance('#swfupload-control');
         swfu.addPostParam("action","save_gallery_cover");
         swfu.addPostParam("cookie",encodeURIComponent(document.cookie));
         swfu.addPostParam("gallery_id",j("#gallery_cover_upload_form #galleriy_id").val());
         swfu.addPostParam("_wpnonce",j("input#_wpnonce-save-gallery-cover").val());
         
       // populate_post_params_for_media();//populate the post parameters
         guploader.swfupload('startUpload');
        return false;

    
});

/**
 * @desc Bulk Media Upload Handling
 */
j("#bulk_upload_media_submit").live('click',
		function() {
        populate_post_params_for_media();//populate the post parameters
         guploader.swfupload('startUpload');
        return false;
});


/*****************************Inline media operations*****************/

/**
 * Editing media Inline
 */
/**
 * @desc Make the media editable
 * */
 j(".media .edit-delete a.edit").live('click',
		function() {
            var media = j(this).parent().parent().parent().get(0);
             make_media_editable(media);
           return false;
        });

//cancel media edit operation

j(".media .media-inline-actions .cancel").live("click",function(){
    var media=j(this).parent().parent().parent().get(0);
    j("form",media).hide();
    j(".media-content",media).show();

    // hide_and_show(gdiv,html);


    return false;
});
/**
 * @desc Save media Information
 *
 * */
j(".media .media-inline-actions .save").live("click",function(){
    var media=j(this).parent().parent().parent().get(0);//the gallery div
    var id=get_id(media);//get the id of this media
 //so we have media id now build a request object
j.post( ajaxurl, {
				'action': 'inline_update_media',
                'media_id':id,
				'cookie': encodeURIComponent(document.cookie),
                'media_title':j("#media_title",media).val(),
                'media_status':j("#gallery_status",media).val(),//needs change
                'media_description':j("#media_description",media).val(),
				'_wpnonce':j("#_wpnonce-edit-save-media",media).val()

			},
function(response){
             response=JSON.parse(response);
             if(response.error!=undefined){
                     notify(response.error.msg,1);
                        return false;
                }
           replace_media(response.data,media);
       		 
			});
     return false;
});

/**
 * Deleting media inline
 */
j(".media .edit-delete a.delete").live("click",function(evt){

var media_div=j(this).parent().parent().parent().get(0);

var id=get_id(media_div);
var url=j(this).attr("href");
var nonce=get_nonce(url);
j.post( ajaxurl, {
				action: 'delete_media',
				'cookie': encodeURIComponent(document.cookie),
                'media_id':id,
				'_wpnonce': nonce
			},
			function(response){
                 response=JSON.parse(response);
                 if(!response.error){
                     delete_media(response.data.id)
                     notify(response.data.msg);}
                  else
                      notify(response.error.msg,1);
			});

   return false;
});

/*** Pretty photo**/
//j(".media-linked").each(function(){
//
//var href=j(this).attr("href");
//href=href+"?pf=true&iframe=true&width=100%&height=100%";
//j(this).attr("href",href);
//
//});
//j(".media-linked").prettyPhoto();

/**
 * For Allowing User to post first comment to a media Item when the media item has no entry in the activity table
 * Thanks to @apeatling, this function is taken from bp-default/_inc/global.js but slightly modified
 */
j("input#gallery-new-comments-submit").click( function() {
		var button = j(this);
		var form = button.parent().parent().parent().parent();

		form.children().each( function() {
			if ( j.nodeName(this, "textarea") || j.nodeName(this, "input") )
				j(this).attr( 'disabled', 'disabled' );
		});

		j( 'form#' + form.attr('id') + ' span.ajax-loader' ).show();

		/* Remove any errors */
		j('div.error').remove();
		button.attr('disabled','disabled');

		/* Default POST values */
		var object = '';
		var item_id = j("#whats-new-post-in").val();
		var content = j("textarea#whats-new").val();
                var current_component=j("#whats-new-post-object_component").val();
		/* Set object for non-profile posts */
		if ( item_id > 0 ) {
			object = j("#whats-new-post-object").val();
		}

		j.post( ajaxurl, {
			action: 'gallery_post_update',
			'cookie': encodeURIComponent(document.cookie),
			'_wpnonce_post_update': j("input#_wpnonce_post_update").val(),
			'content': content,
			'object': object,
                        'component_type':current_component,
			'item_id': item_id,
                        'component_id': cur_component_id
		},
		function(response)
		{
			j( 'form#' + form.attr('id') + ' span.ajax-loader' ).hide();

			form.children().each( function() {
				if ( j.nodeName(this, "textarea") || j.nodeName(this, "input") )
					j(this).attr( 'disabled', '' );
			});

			/* Check for errors and append if found. */
			if ( response[0] + response[1] == '-1' ) {
				form.prepend( response.substr( 2, response.length ) );
				j( 'form#' + form.attr('id') + ' div.error').hide().fadeIn( 200 );
				button.attr("disabled", '');
			} else {
                            //hide the form
                            j(form).remove();
				if ( 0 == j("ul.activity-list").length ) {
					j("div.error").slideUp(100).remove();
					j("div#message").slideUp(100).remove();
					j("div.activity").append( '<ul id="activity-stream" class="activity-list item-list">' );
				}

				j("ul.activity-list").prepend(response);
				j("ul.activity-list li:first").addClass('new-update');
				j("li.new-update").hide().slideDown( 300 );
				j("li.new-update").removeClass( 'new-update' );
				j("textarea#whats-new").val('');

				/* Re-enable the submit button after 8 seconds. */
				setTimeout( function() {button.attr("disabled", '');}, 8000 );
			}
		});

		return false;
	});
    

/**
 * Publish Media to activity stream
 */

j("#publish_gallery_activity a").live('click',function(){
 var url = j(this).attr('href');
            var gid=get_var_in_url(url,'gallery_id');
	    var nonce = get_nonce(url);
            var action=get_var_in_url(url,"publish");
            
       j.post( ajaxurl, {
			action: 'publish_gallery_to_activity',
			'cookie': encodeURIComponent(document.cookie),
                        'gallery_id':gid,
                        'publish_status':action,
			'_wpnonce': nonce

			},
		   function(response){
                       response=JSON.parse(response);
                        if(response.error!=undefined)
                             show_message(response.error.msg,1);
                        else
                            show_message(response.msg,0);
                     });
       	return false;

       });


j("#activity_upload_media_submit").live("click",function(){
    
    populate_post_params_for_activity();//populate the post parameters
         guploader.swfupload('startUpload');
        return false;
    
    
    
});//end of activity upload section
    
// setup player
	//flowplayer("player", "http://releases.flowplayer.org/swf/flowplayer-3.1.5.swf", {



	// use playlist plugin to enable playlist items work as movie clips
	//}).playlist("#playlist");

});

//global function
function gallery_activate_player(){
jQuery(".player_wrapper").each(function(){
       jQuery("a.player").each( function(){
			flowplayer(this,  
					{
					src:bp_video_player_url,
					bgcolor:"#ffffff" //flashembed params
					}, 
				{
				plugins: {
					audio: {
                      url: bp_audio_player_url
                       }
                  },
				  wmode: 'opaque' 
				 
    // use playlist plugin to enable playlist items work as movie clips
}).playlist("div.playlist");
//,jQuery(this)).get(0)
});
});
}