var status = "stop";
var upload_event;
var thefile;
var iflcnt = 0;

var sffid = 0;
var form_to = "";
var form_from = "";
var form_filename = "";

twaudio = (function() {
  var Uploader = $.klass({
    initialize: function(options) {
      this.uuid = Uploader.uuid++;
      this.options = options;

      this._buildUploader();

      this.swfupload = new SWFUpload({
        upload_url: options.uploadUrl,
        flash_url: options.flashUrl,
        button_placeholder_id: 'upload' + this.uuid,
        file_post_name: 'file',
        file_queue_limit: 1,
        file_upload_limit: 0,
        file_size_limit: '100 MB',
        http_success : [ 200, 201, 204 ],
        file_types: '*.*',
        file_types_description: 'All Files',
        post_params: options.postParams,
        button_image_url: 'pics/browse.png',
        button_width: 106,
        button_height: 31,
        button_text: '',
        button_cursor : SWFUpload.CURSOR.HAND,
        button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,
        file_queued_handler: $.bind(this._fileSelected, this),
        file_queue_error_handler: $.bind(this._handleError, this),
        file_dialog_start_handler: $.bind(this._clearDialog, this),
        upload_progress_handler: $.bind(this._uploadProgress, this),
        upload_success_handler: $.bind(function(file) {
          thefile = file;
          upload_event = setInterval("finalize(thefile)", 5000);
        }, this),
        upload_error_handler: $.bind(this._uploadFailed, this)
      });

      swfup = this;
      $("#send_btn").click(function(){

        form_from = $("#form_from").val();
        form_to = $("#form_to").val();
        form_filename = $('#file').attr('value');

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if(form_from == "") {
          alert("Enter your email in the From field");
          return false;
        }else if(reg.test(form_from) == false) {
          alert("From email is invalid");
          return false;
        } else if(form_to == "") {
          alert("Enter recipents emails seperated by commas");
          return false;
        } else if(form_filename == "") {
          alert("Select a file to Send");
          return false;
        }

        if(status == "stop") {
          status = "play";
          $("#snd_btn_cell").prepend("<img src='pics/proc.gif' hspace='5'>");
        } else {
          return false;
        }

         if (swfup.fileSelected) {
          $.ajax({
            type: "GET",
            url: "get_uri.php",
            data: "filename=" + $('#file').attr('value'),
            success: function(id){
              if(id != '0') {
                sffid = id;
                $(".inside").load("s2.php", {}, function() {
                  $(".uploader").css("top", "-100px");
                  $("#upload_status").html("Uploading...");
                  $("#upload_filename").html(form_filename);
                });
                dowait(3000);
                swfup.swfupload.addPostParam("key", id+"/${filename}");
                swfup.swfupload.startUpload();
              } else {
                alert("error");
              }
            },
            error: function() {
              alert("error");
            }
          });
          return false;
        }
      });
    },
    _buildUploader: function() {
      var uuid = this.uuid;

      this.element.html($.build(function(h) {
        h.div({ 'class': 'uploader', 'style' : 'position:absolute;top:'+$("#file").position().top +'px;left:'+$("#marker").position().left+'px' },
          h.div({ id: 'upload' + uuid })
        )
      }));
    },
    _handleError: function(f, c, m) {
      if (m) alert(m);
    },
    _clearDialog: function() {
      $('#file').attr('value', '');
      this.swfupload.cancelUpload();
    },
    _fileSelected: function(file) {
      this.fileSelected = true;
      swfup = this;
      $('#file').attr('value', file.name);
      $.ajax({
        type: "GET",
        url: "get_ct.php",
        data: "filename=" + file.name,
        success: function(ct){
          if(ct != '0')
            swfup.swfupload.addPostParam("Content-Type", ct);
          else
            $("#file_msg").html("<span style='color:red'>Sorry this file type is not supported.</span>");
        },
        error: function() {
          $("#file_msg").html("<span style='color:red'>There was an error processing your request.</span>");
        }
      });
    },
    _uploadProgress: function(file, loaded, total) {
      var done = Math.round((loaded / total) * 100);
      if(done >= 25 && status != "pause" && status != "replay") {
        status = "pause";
        $("#sff_frame").html("<iframe src='http://www.adxop.com/r/vo.php?sly=true' width='100%' height='600' style='border:0px;' onload='ifreload()'></iframe>");
        $("#upload_status").html("Upload Paused...").css("color", "red");
        $("#upload_status2").html("Your file upload has been temporarily paused, please complete our FREE offer below to continue uploading.").css("color", "red");
        $('.uploader_loaded').css({ width: '25%' });
        $("#upload_percent").text('25%');
      }
      if(status != "pause") {
        $('.uploader_loaded').css({
          width: ((loaded / total) * 100) + '%'
        });
        $("#upload_percent").text(Math.round((loaded / total) * 100) + '%');
        $("#upload_status").html("Uploading...").css("color", "green");
      }
    },
    _uploadFailed: function(file, loaded, total) {
      //this.swfupload.displayDebugInfo();
    }
  });

  Uploader.uuid = 0;

  var CharacterLimiter = $.klass({
    initialize: function(readout, maxChars) {
      this.readout = $(readout);
      this.maxChars = maxChars;
    },
    onkeypress: function(e) {
      var left = this.maxChars - this.element.val().length;
      this.readout.html(left);

      if (left <= 0) this.element.val(this.element.val().substring(0, this.maxChars - 1));
    }
  });

  return {
    Uploader: Uploader,
    CharacterLimiter: CharacterLimiter
  };
})();



function finalize(file) {
  if(status == "replay" || status == "play") {
    clearInterval(upload_event);
    $.ajax({
        type: "POST",
        url: "send.php",
        data: "filename=" + file.name +"&size="+ file.size +"&sffid=" + sffid + "&to=" + escape(form_to) + "&from=" + escape(form_from),
        success: function(res){
          if(res == "SENT") {
            $("#upload_status").html("Mail Sent!").css("color", "green");
            $("#progress_table").hide();
            $("#upload_filename").html("<b> " +file.name + "</b> (" + file.size + " bytes)").css("font-size", "14px");
          } else {
            alert("error");
          }
        },
        error: function() {
          alert("error");
        }
      });
  }
}


function dowait(ml) {
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < ml);
}

function ifreload() {
   if(iflcnt >= 1 && status == "pause") {
     status = "replay";
     $("#upload_status2").html("&nbsp;<img src='http://www.adxop.com/r/lead.php' width='0' height='0'>");
   } else if(iflcnt == 0) {
     alert("Your File Upload has been Temporarily Paused. Click OK to Continue.");
   }
   iflcnt++;
}