var frameId = 'frame_ID';      //hidden frame id
var jFrame = null;                //hidden frame object
var formId = 'form_ID';         //hidden form id
var jForm = null;                 //hidden form object
var token = "random_token";  //random session token, for server-side script use
var fileMax = 100;                  //maximum number of file to be uploaded
var fileCount = 0;               //file counter
var uploadUrl = "/save.php"; //where to handle uploaded image
 
 
$(document).ready(function(){                     
 
jForm = createForm(formId,token);       //create hidden form
jFrame = createUploadIframe(frameId)   //create hidden iframe
 
//append hidden form to hidden iframe, change top and left to a large negative number to make it invisable
jForm.appendTo('body').css({position: 'absolute',top: '150px',left: '350px'});         
 
jForm.attr('target',frameId);              //make form target to iframe
 
 
$("#inp").bind('change',startUpload);   //bind onchange function to input element
 
function startUpload(){
   if(jForm!=null){               
      jForm.remove();                        //re-create hidden form
      jForm = createForm(formId,token);
      jForm.appendTo('body').css({position: 'absolute',top: '150px',left: '350px'});
      jForm.attr('target',frameId);
   }
 
   var newElement = $(this).clone(true);   //clone input element object
   newElement.bind('change',startUpload); //bind onchange function. start uploading when file selected
   newElement.insertAfter($(this));          //insert clone object to current input element object
   $(this).appendTo(jForm);                    //move current input element along with its value to hidden form
 
 
   $("loading").show();               //show loading icon 
   jForm.submit();                     //let's upload the file
 
   jFrame.unbind('load');                  
   jFrame.load(function(){               //bind onload function to hidden iframe
 
      //get response message from hidden iframe
      var myFrame = document.getElementById($(this).attr('name'));   
      var response = $(myFrame.contentWindow.document.body).text();
 
      /*
      * you may handle upload status from reponse message.
      * in this example, upload succeeded if message contains image url, otherwise, alert reponse message
      */
 
      if(response.indexOf('http://')!=-1){ //upload successfully
 
         addUpload(Math.floor(Math.random()*100),response);   //show thumbnails, assign a id for future reference
         fileCount++;
         if(fileCount >= fileMax){                     //reach maximum upload file, disable input element
            $("#inp").attr('disabled','disable');
         }
      }else{  //error
         alert(response);
      }
 
      //hide loading icon
      $("loading").hide();
   });
}
 
 
});
 
function createUploadIframe(id){
   //set top and left to make form invisible
   return $('<iframe width="200" height="200" name="' + id + '" id="' + id + '"></iframe>')
         .css({position: 'absolute',top: '270px',left: '350px'})
         .appendTo('body');
}
 
function createForm(formId,token) {
      return $('<form method="post" action="'+uploadUrl+'" name="' + formId + '" id="' + formId + 
            '" enctype="multipart/form-data" style="position:absolute;border:1px solid #f00;'+
            'width:200px;height:100px">' +
            '<input type="hidden" name="token" value="' + token + '"/>' +
            '</form>');
}
 
function addUpload(id,img){
   var div = $(document.createElement('div')).attr('id',id);
   div.html("<img src='"+img+"'> ");
 
   //add remove thumbnail link
   var rem = $(document.createElement('a')).attr('alt',id).attr('href','javascript:;').text("Remove").click(removeUpload);      
 
   rem.appendTo(div);
   div.appendTo("#uploaded_thumb");
}
 
function removeUpload(e){
   var removeId = $(e.target).attr('alt');
   $('#'+removeId).remove();
   if(fileCount>0) fileCount--;
   $("#inp").removeAttr('disabled');
}