var UPLOAD_IFRAME_LIST = null;
var CUR_UPLOAD_FRAME = null;
var BATCHID_URL = "/ajaxgateway.php?action=GetBatchId";
var GET_FTF_URL = "/ajaxgateway.php?action=GetFtf";
var GET_CONTACTS_URL = "/ajaxgateway.php?action=GetContacts";
var GET_SUBUSER_URL  = "/ajaxmultiusergateway.php?action=GetDetails";
var PRE_PPU_VOID_URL = "/ajaxgateway.php?action=VoidPpu";
var BATCH_ID = null;
var MAX_RECIPIENTS_GUEST_ACCT_TYPE = 3;
var MAX_RECIPIENTS_LITE_ACCT_TYPE = 3;
var MAX_RECIPIENTS_GUEST_CHAR = 128;
var MAX_ALLOWED_MSG_CHAR = 100;
var FILE_SIZE = 0;
var UPLOAD_SIZE_CONSTRAINT = 20*1024*1024;
var UPLOAD_SIZE_LIMIT = 100*1024*1024; //100 MB
var UPLOAD_SIZE_LIMIT_FOR_EXPRESS = 60*1024*1024; //60 MB
var CUR_FTF;
var MAX_INVITATIONS = 3;
var MY_ACCOUNT = false;
var USER_CONTACTS = new Array();
var SUBUSER_DETAILS = '';
var FIRST_NAME='';
var LAST_NAME='';
var filter  = /^([\sa-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9\s]{2,4})+$/;
var FileForwardID_URL = "/ajaxgateway.php?action=SaveFileForwardInfo";
var RCPT_LEN = 0;
var uploadState='';
var customDomain=false;
var newDomain=false;
var refererDomain='';

function generate_random_number(){
  var randomnumber=Math.floor(Math.random()*999999999);
  return randomnumber;
}

function validateAllEmails(){
var ff = ge("rcpt").value;
  ff = ff.replace(/\;/gi,',');
  f_arr = ff.split(',');
   if(f_arr.length==1 && trim(f_arr[0])=="") {
       alert(ENTER_EMAIL);
       return false;
   }
  else {
    if (!validateMaxInvitations(f_arr.length)){
      return false;    
     }
    for(i=0; i < f_arr.length; i++){
      	if(!filter.test(trim(f_arr[i]))){
        	alert(EMAIL+ f_arr[i] +INVALID_FORMAT);
	        return false;
        }
     }
  }
  return true;
}

function validateUrl(field,fieldname){
var iChars ="<>()\'\"";
for (var i = 0; i < field.value.length; i++) {
 if (iChars.indexOf(field.value.charAt(i)) != -1) {
     alert ("Your "+ fieldname+ " has special characters. \nThese are not allowed.\n Please remove them and try again.");
     return false;
    }
 }
return true;

}

function validateString(field,fieldname){
//var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
var iChars ="<>()?\'\"";
for (var i = 0; i < field.value.length; i++) {
 if (iChars.indexOf(field.value.charAt(i)) != -1) {
     alert ("Your "+ fieldname+ " has special characters. \nThese are not allowed.\n Please remove them and try again.");
     return false;
    }
 }
return true;

}

function validateStringForTextArea(field,fieldname){
var iChars = "@#%^*+=[]|\<>";
for (var i = 0; i < field.value.length; i++) {
 if (iChars.indexOf(field.value.charAt(i)) != -1) {
     alert ("Your "+ fieldname+ " has special characters. \nThese are not allowed.\n Please remove them and try again.");
     return false;
    }
 }
return true;

}

function validateMaxInvitations(recipientsNum)
{
	if (recipientsNum > MAX_INVITATIONS)
 	{
   		alert(MAX_INVITATION_ALLOWED + MAX_RECIPIENTS_GUEST_ACCT_TYPE);
	    return false;
 	}
	else return true;
}


function display_total_price()
{
  CreditForm = ge('cc_info');
	amount = gfe(CreditForm, 'total-amount');
	amount.innerHTML = '$'+TOTAL_PPU_PRICE;
}


function send_email(type)
{
	if(type=='yes'){
	    window.location = YSI_BASE_URL+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
	}
	else
	  window.location = YSI_BASE_URL+"/transfer.php";
}


function void_batch(type)
{
    if(type == 'yes')
    {
        // In case of ppu, void the transaction
        window.location = YSI_BASE_URL+"/transfer.php?action=batch_void&batch_id="+BATCH_ID;
    }
    else
    {
        //Nothing to do
    }
}

var punctuation = '.,;!? ';
function trunc(s,size)
{
  if(!size)size=30;
  if(s.length<=size)return s;

  p=-1;

  for(var i=0;i<size;i++)
    if(punctuation.indexOf(s.charAt(i))!=-1)p=i;

  if(p==-1)p=size-1;

  return ''+s.substr(0,p)+'...';
}


function switch_all_mode(iframe_list, page)
{
  for (i = 0; i < iframe_list.length; i++)
  {
  	try{
	  	if (iframe_list[i]["remove_elem"])
	  	{
	  		iframe_list[i]["remove_elem"].style.display = "none";
	  	}
  	}
  	catch(e)
  	{// let it pass through
  	}
    if (page != 'myact' && is_safari){
      gfe(iframe_list[i],"fname").style.marginLeft="300px";
    } 

    if (is_safari && DROPBOX) {
      gfe(iframe_list[i],"fname").style.marginLeft="0px";
    }
    if (!is_safari)
    	gfe(iframe_list[i],"fname").style.display="none";
    if(!getFilename(gfe(iframe_list[i],"fname").value)=='') {
      file_name = '<div style="color:#1d499f; font-family: Verdana; font-size:11px;"><b>Selected file: '+ trunc(getFilename(gfe(iframe_list[i],"fname").value),30) + '</b></div>';
      gfe(iframe_list[i],"selected-fname").innerHTML= file_name;
    } else {
      iframe_list[i].style.display="none";
    }
    iframe_list[i].style.height = "40px";
    if(!DROPBOX=='')
      iframe_list[i].style.marginLeft = "40px";
  }	
}    

function check()
{
  var id = document.getElementById("step-two-subdiv");
  if (id.style.display=='none')
  {
    id.style.display='inline';
  } else {
    ge("pass").value = '';      //make the value to blank if user uncheck the password protected, after entering some values
    ge("pass_conf").value = '';
    id.style.display='none';
  }
}

function check_pdf() {
  var id = parent.ge("step-two-subdiv-pdf");
  if (id.style.display=='none') {
    id.style.display='inline';
  }
}

function validate_upload(upload_iframe_list, acct_type)
{
  if(SHOW_ADS=='true')
    setTimeout('loadAdFrame()', 500);
  invalid_count = 0;
  return_value = true;
  for (i = 0; i < upload_iframe_list.length; i++)
  {
  	fname = gfe(upload_iframe_list[i],"fname").value;
    if(fname == null || fname.length == 0) {
      invalid_count++;
    }
  }	
  
  var upload_ff_file_count = upload_iframe_list.length;
  if(ge("ff_file_forward") && ge("ff_file_forward").value == "true")
  {
    str = ge("ff_file_ids").value
    arr_str = str.split(";");
    upload_ff_file_count = arr_str.length + upload_ff_file_count;
  }

  if(invalid_count == upload_ff_file_count) {
    alert(SELECT_FILE_FOR_UPLOAD);
    return false;
  }
  
  //Check the file size and alert user accordingly

//for checking  if sender has provided email address while uploading via dropbox
  if(!DROPBOX=='')
  {
    //Bug Fix::7827::gl.manish::12/04/2008 Start
    var from = unescape(trim(ge("from").value));

    from = from.replace(/\;/gi,',');
    if(from.lastIndexOf(',') == from.length-1) {
      if(from.length >= from.lastIndexOf(','))
      {
        alert('Please enter the valid email address. Remove (, or ;) from end of the email address.');
        return false;
      }
    }

    arr_from = from.split(",");
    //Bug Fix::7827::gl.manish::12/04/2008 End

    if(from.length == 0)
    {
      alert(PROVIDE_EMAIL_ADDRESS);
      return false;
    }
    //Bug Fix::7827::gl.manish::12/04/2008 Code Start
    //if multiple email addresses are entered then display the error message
    else if(arr_from.length > 1)
    {
      alert('Please enter single email address.');
      return false;
    }

    //Validate email format
    if(!filter.test(from)){
      alert('Email address you provided is not in valid format.');
      return;
    }
    //Bug Fix::7827::gl.manish::12/04/2008 Code End

  }

		 //checking file size
		//Bug Fix::7897::gl.manish::12/19/2008
		if(DROPBOX=='' &&  (((acct_type=='GST' || acct_type=='BAS') && (!ge("fid0") || !ge("fid0").checked)) ||acct_type=='PL1')) {
    FORMATTED_FILE_SIZE = FILE_SIZE;
    
			var frm = ge("from").value;
    
    if(FILE_SIZE < 1024)
      FORMATTED_FILE_SIZE = FILE_SIZE + " Bytes";
    else if(FORMATTED_FILE_SIZE > (1024 * 1024)) {
      FORMATTED_FILE_SIZE = Math.round(((FORMATTED_FILE_SIZE / (1024*1024))*100)/100) + " MB";
    } else if(FORMATTED_FILE_SIZE > 1024)
      FORMATTED_FILE_SIZE = Math.round(((FORMATTED_FILE_SIZE / 1024)*100)/100) + " KB";

    var max_size = document.getElementById("acctTypeMaxSize").value;
    var partner = document.getElementById("partner").value; 
    max_size = parseInt(max_size);


    if(UPLOAD_REDIRECT == 'true') {
      if(frm == ""){
           if( (FILE_SIZE > ( UPLOAD_SIZE_CONSTRAINT+8196)) && (FILE_SIZE <=(UPLOAD_SIZE_LIMIT +8196))){ // file size >20MB and <=100MB
               //remove the lock page listener, since the user is redirected to signup/login page
               YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);
               window.location = "https://"+YSI_BASE_HOST+"/upload.php?action=register_lite";
               return false;
           }
            else if( FILE_SIZE >(UPLOAD_SIZE_LIMIT +8196)){                                       //file size >100 MB
           
               YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);
               window.location = "https://"+YSI_BASE_HOST+"/upload.php?action=large_file";
               return false;
           }        
      }else if(frm !=""){
            if( (FILE_SIZE > ( UPLOAD_SIZE_CONSTRAINT+8196)) && (FILE_SIZE <=(UPLOAD_SIZE_LIMIT +8196))){ // file size >20MB and <=100MB  
                YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);
                window.location = "https://"+YSI_BASE_HOST+"/upload.php?action=with_email&frmemail="+frm;
                return false;
             }
             else if(FILE_SIZE >(UPLOAD_SIZE_LIMIT +8196)){
            
                    YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);
                    window.location = "https://"+YSI_BASE_HOST+"/upload.php?action=withemail_largefile&frmemail="+frm;
                    return false;
             } 

        }
    }
     // if  Lite user uploads file >100MB and has never used PPU or was Paid user before redirect it

      if(acct_type == "BAS" && (FILE_SIZE > (UPLOAD_SIZE_LIMIT +8196)))
      {
           var is_paid_ppu = ge("has_paid_before").value;
           if(is_paid_ppu == 0) // has never done any credit card purchase
           {
             YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);
             parent.show_ppu_subscribe_modal();
             return false;
           }else 
             {
                  window.location = "https://"+YSI_BASE_HOST+"/settings.php?es=186";
                  return false;
              }
      } 
  }


   
// Checking for File download days for  New Tier Phase-2 

 if(DROPBOX=='')
 {
   var pattern =  /^(0)$|^([1-9][0-9]*)$/;
   var download_days = ge("download_days").value;
   
   if(isNaN(download_days))
   {
     if ( (download_days=='Unlimited') && (acct_type=='BS2' || acct_type=='BUS' || acct_type=='ADM' || acct_type=='SUB'))
	 {
		//return true;
     }
	 else {
           alert(STRING_NOT_ALLOWED);
           return false;
     }
    }
    else  if( (download_days=='') ||(download_days <= 0) || ( !pattern.test(download_days.substr())) ){
       alert(INVALID_DOWNLOAD_DAYS);
       return false;
    }
    else if (  (acct_type == 'PRO'  &&  (download_days >500 || isNaN(download_days )))  ||   (acct_type == 'PL1'  &&  (download_days >200 || isNaN(download_days )))    ){
      alert(INVALID_DOWNLOAD_DAYS);
      return false;
    }
 }

// for checking null for password
  if(ge("passpro").checked)
  {
    if( (! ge("passwd").value=='') && (! ge("pass_conf").value=='')  ){
      if(!( ge("passwd").value==ge("pass_conf").value)){
        alert(PASSWORD_NOT_MATCHING);
        return false;
      }
      else if  (ge("passwd").value.length< 5)  {
        alert(PASSWORD_LENGTH_INCORRECT);
        return false;
      }
    }
    else {
      if  (! ge("passwd").value=='')
        alert(CONFIRM_PASSWORD)
      else
        alert(REENTER_PASSWORD);
        return false;
    }
  } 


  var recipient = ge("rcpt").value;
  if(recipient.length == 0)
  {
    alert(PROVIDE_RECIPIENT_EMAIL);
    return false;
  }

  //Recipient Email(s) text field in the guest send form must be limited to 128 characters
//  if(recipient.length > MAX_RECIPIENTS_GUEST_CHAR && acct_type == 'GST')
 // {
 //   alert(LIMIT_RECIPIENT_GUEST_EMAIL + MAX_RECIPIENTS_GUEST_CHAR + ".");
  //  return false;
//  }


  var ff = ge("rcpt").value;
  ff = ff.replace(/\;/gi,',');
  ff = ff.replace(/^\s*|\s*$/g,"");
  if(ff.lastIndexOf(',') == ff.length-1) {
    if(ff.length >= ff.lastIndexOf(','))
      ff = ff.substr(0,ff.lastIndexOf(','));
  }

  f_arr = ff.split(',');
  RCPT_LEN = f_arr.length;

  var unique_flag = true;
  f_arr.sort();
  for (var i=0; i<f_arr.length - 1; i++)
  {
    if (trim(f_arr[i]) == trim(f_arr[i+1]))
	{
      unique_flag = false;
      break;
	}
  }

  if(unique_flag == false)
  {
      alert('Please remove the duplicate Recipient\'s email.');
	  return;
  }

  if(f_arr.length == 1) {
    if(!filter.test(ff)){
      alert('Recipient\'s email you provided is not in valid format.');
      return;
    }
  }
  else {
    if (!validateMaxAllowedRecipients(acct_type, f_arr.length))
    {
      return false;
    }
    for(i=0; i < f_arr.length; i++){
      if(!filter.test(trim(f_arr[i]))){
        alert('Email '+ f_arr[i] +' is not in valid format.');
        return;
      }
    }

  }
 
  if ((acct_type == 'BAS') || (acct_type == 'GST'))
  {
    if (ge("msg").value.length > MAX_ALLOWED_MSG_CHAR)
    {
      alert(MAX_LIMIT_MESSAGE_TEXT + MAX_ALLOWED_MSG_CHAR +CHARACTERS);
      ge("msg").value = ge("msg").value.substring(0, MAX_ALLOWED_MSG_CHAR);
      return false;
    }
  }

 //Bug Fix::7319::Anamika.gl::10/23/2008
  if( DROPBOX=='' && parent.ge("fid5") && parent.ge("fid5").checked && (PDF_INVALID_FLAG || checkPdfStatus(true) == 0)){
		var result = alert_no_supported_file_continue();
//Bug Fix::7534::Anamika.gl::10/30/2008
			parent.ge("fid5").checked = false;
		return result;
  }else{
		return true;
  }
 
  var from = ge("from").value;
  if(from.length == 0 || filter.test(from)) {
    return true;
  }
  else {
    alert(EMAIL_INVALID_FORMAT);	
    return false;
  } 
}


function validateMaxAllowedRecipients(acct_type,recipientsNum)
{         
         
 if(DROPBOX ==''){
   var recipients_allowed = 0;  
   if(ge("num_recipients"))  
     recipients_allowed = ge("num_recipients").value;  

   if ((recipients_allowed !='NULL') && (recipients_allowed !='') &&   recipientsNum > recipients_allowed )
   {         
      var message=MAX_RECIPIENT_ALLOWED_FOR_USER ;
     if (acct_type == 'GST')  {
       message= MAX_RECIPIENT_ALLOWED_FOR_GST_USER ;
      }
     else if (acct_type == 'BAS')  {
       message=MAX_RECIPIENT_ALLOWED_FOR_LITE_USER ;
      }
   alert(message + recipients_allowed);
   return false;
  } 
 }  
 return true;
}


function showSendingAd()
{
  ge("sending-ad").setAttribute('src', '/transfer.php?action=upload_ad');
	window.setTimeout('showSendingAd()', 30000);
}

function upload_file()
{
  var upload_form = ge('tform');

  ge('file-name').innerHTML = getFilename();
	setTimeout('loadProgressBar()', 500);
    
  upload_form.action = upload_form.action + '/' + PROGRESS_ID;
  upload_form.target="_self";
  
  upload_form.submit();

}

function loadProgressBar() {
  
  progFrame = ge('progressFRM');
  progFrame.setAttribute('visbility', 'visible');
  frameSrc = PROGRESS_URL+'/progbar_ui.html';
  progFrame.setAttribute('src', frameSrc);

}

function loadAdFrame() {

  if(SECURE_UPLOAD=='true') {
    ge('content-frm').src = 'https://' + YSI_BASE_HOST +'/advert.php?action=display_medium&rfs=1&intvl=30&scrid=https_registeredsend';
  }
  else {
    ge('content-frm').src = YSI_BASE_URL+'/advert.php?action=display_medium&rfs=1&intvl=30&scrid=UploadProgress_300';
  }

}


function getContacts()
{
	var cList = window.open("/contacts.php?action=list", "list", "width=400,height=460,resizable=1");
	if (window.focus) {
	    cList.focus();
	}
	return false;
}

function ajax_getSubContactsFile(user_id,fname,lname)
{
         url = GET_SUBUSER_URL;
        url = url + "&user_id="+user_id+"&fname="+fname+"&lname="+lname+"&tmp="+generate_random_number()+"&";
        AJAX_CALLBACK_SUBUSER.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_SUBUSER);
}
 
function rememberEmail()
{
	setCookie("rememberme", ge("from").value, null);
}

function setCookie(cname, value, expire_ts)
{
	var expires = expire_ts;
  if (expires == null)
  {
		var date = new Date();
		date.setTime(date.getTime()+(60*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = cname + "="+value+expires+"; path=/";
}

function eraseCookie(){
	document.cookie = 'rememberme=; -1; path=/';
}

function getFilename(fileName)
{
  if (fileName != "") {
    if (fileName.match(/^(\\\\|.:)/)) {
      var temp = new Array();
      temp = fileName.split("\\");
      var len = temp.length;
      fileName = temp[len-1];
    } else {
      temp = fileName.split("/");
      var len = temp.length;
      if(len>0)
        fileName = temp[len-1];
    }
  }  
  return fileName;
}

function updateFilename()
{
  var fileName = getFilename();
  if (fileName != '') {
      ge("show_filename").value = fileName;
      lastfileselected = fileName;
	}
}

function trim(str)
{
	return escape(str.replace(/^\s*|\s*$/g,""));
}


function pdf_flag() {
  var pdf_flag = true;
  if (ge('fid5') == null) {
    pdf_flag = false;
  }
  return pdf_flag;
}


function remove_upload(remove_el, iframe_el)
{
	// remove from iframe remove list:
	for (i=0; i < UPLOAD_IFRAME_LIST.length; i++)
	{
		if (iframe_el == UPLOAD_IFRAME_LIST[i])
		{
			UPLOAD_IFRAME_LIST.splice(i, 1); // remove the item
		}
	}

    if (pdf_flag()) {
      if (!parent.ge("pdf-cell").hasChildNodes()) {
        parent.rebuild_pdf_div();
      }
      var topDiv = parent.ge('list-of-files-topdf');
      var i = 0;
      while (topDiv.hasChildNodes()) {
        var subDiv = topDiv.childNodes[i];
        if (subDiv == null) {
          break;
        }
        var innerChkBox = subDiv.childNodes[0];
        var if_id = innerChkBox.getAttribute("if_id");
        if (iframe_el.id == if_id) {
          if (topDiv.childNodes.length == 1) {
            parent.ge("fid5").checked = false;
            parent.ge("step-two-subdiv-pdf").style.display="none";
          }
          topDiv.removeChild(subDiv);
        }
        i++;
      }
    }

	remove_el.parentNode.removeChild(remove_el);
	iframe_el.parentNode.removeChild(iframe_el);
    if (pdf_flag()) {
      if (parent.checkPdfStatus(false) <= 1) {
        if (!parent.ge("pdf-cell").hasChildNodes()) {
          parent.rebuild_pdf_div();
        }
        var pdf_cell = parent.ge("pdf-cell");
        var i = 0;
        while (pdf_cell.hasChildNodes()) {
          pdf_cell.removeChild(pdf_cell.childNodes[i]);
        }
        i++;
      }
    }
}

function create_remove_elem(iframe)
{
	remove_elem = ge("remove_elem_id");
	newelem = remove_elem.cloneNode(true);
	newelem.onclick = function(){remove_upload(this, iframe);};
	return newelem;
}

function create_upload_iframe()
{
	ifm = ge("file_upload_iframe");
	newiframe = ifm.cloneNode(true);

	newiframe.setAttribute("upload_state", "INIT");
//	newiframe.setAttribute("upload_fname", fname);
	newiframe.setAttribute("upload_rcpt", ge('rcpt').value);
	newiframe.setAttribute("upload_from", ge('from').value);
	newiframe.setAttribute("upload_msg", ge('msg').value);
	newiframe.setAttribute("upload_subject", ge('subject').value);
	newiframe.setAttribute("upload_file_subject", ge('upl_subject').value);
    
	//Bug Fix::#7897::Pushpendra.gl::12-19-08 Start
  if(ge('passwd'))
		newiframe.setAttribute("upload_pass", ge('passwd').value);
	if(ge('expiration_time'))
		newiframe.setAttribute("upload_expiration_time", ge('expiration_time').value);
	if(ge('download_days'))
		newiframe.setAttribute("download_days", ge('download_days').value);
	//Bug Fix::#7897::Pushpendra.gl::12-19-08 End

	var date = new Date();
	newiframe.id="upload_if_" + date.getTime(); 
	newiframe.name = newiframe.id;

	return newiframe;
}

function add_iframe(to_parent_id, hide_remove_elem)
{
    if(MAX_UPLOAD_COUNT <= 1) {
       window.location = '/cms/compareaccounts&es=189';
       return;
    }

	to_parent = ge(to_parent_id);
	
	if (to_parent != null)
	{
		if (UPLOAD_IFRAME_LIST == null)
		{
			init_iframe_list(to_parent_id);
		}

		var upload_file_count = 0;
		upload_file_count = UPLOAD_IFRAME_LIST.length;		
		
		if(ge("ff_file_forward") && ge("ff_file_forward").value == "true")
		{	
		  var str = ge("ff_file_ids").value
		  arr_str = str.split(";");
		  upload_file_count = arr_str.length + upload_file_count;
		}

		if (upload_file_count >= MAX_UPLOAD_COUNT )
		{
			alert (MAX_UPLOAD_LIMIT);
			return false;
		}
	   	newiframe = create_upload_iframe();
		newiframe.style.display = "block";   	
		newiframe.style.height = "26px";   	
   		newremove_el = create_remove_elem(newiframe);

	    if (!hide_remove_elem)
			newremove_el.style.display = "block";	  
		
		newiframe["remove_elem"] = newremove_el;	
		
	 	// add to iframe list
		nextcount = UPLOAD_IFRAME_LIST.push(newiframe);
	   	
		to_parent.appendChild(newremove_el);
		to_parent.appendChild(newiframe);
	}
}

function init_iframe(iframe_id)
{
  iframe = ge(iframe_id);
  if (iframe)
  {
 		pstate = "INIT";
		try{
 				pstate = gfe(iframe, "pstate");
 		}
		catch(e)
		{
		}
		if (pstate != "INIT")
		{  				
  		iframe.setAttribute("upload_state", "INIT");
      if (parent.SPECIFIED_FTF == '') {
        iframe.src = "/process_upload.php";
      } else {
        iframe.src = "/process_upload.php?upload_to="+parent.SPECIFIED_FTF;
      }
  	}
  }
}

function init_iframe_list(parent_name)
{
	parent_elem = ge(parent_name);

	UPLOAD_IFRAME_LIST = new Array();
    
	for (i = 0; i < parent_elem.childNodes.length ; i++)
	{
		child = parent_elem.childNodes[i]; 
                
		if (child.getAttribute && child.style.display == "block")
		{
			try 
			{
	      is_iframe = child.getAttribute("upload_state");
	      if(is_iframe!=null && is_iframe.length>0) {
			iframe = child;
			iframe.setAttribute("upload_state", "INIT");
			iframe.setAttribute("upload_rcpt", ge('rcpt').value);
			iframe.setAttribute("upload_from", ge('from').value);
			iframe.setAttribute("upload_msg", ge('msg').value);
			iframe.setAttribute("upload_subject", ge('subject').value);
            iframe.setAttribute("upload_file_subject", ge('upl_subject').value); 

	    //Bug Fix::#7897::Manish.gl::12-19-08 Start
			if(ge('passwd'))
				iframe.setAttribute("upload_pass", ge('passwd').value);
			else
				iframe.setAttribute("upload_pass", '');

	    if(ge('expiration_time'))
			  iframe.setAttribute("upload_expiration_time", ge('expiration_time').value); 
			else
				iframe.setAttribute("upload_expiration_time", '');

			if(ge('download_days'))
				iframe.setAttribute("upload_download_days", ge('download_days').value); 
			else
				iframe.setAttribute("upload_download_days", '');
			//Bug Fix::#7897::Manish.gl::12-19-08 End

			nextcount = UPLOAD_IFRAME_LIST.push(iframe);
	      }
			}
			catch (e)
			{
			}
		}	
	}

	return UPLOAD_IFRAME_LIST; 
}

function url_encode(str)
{
return escape(str);
}

function start_upload(upiframe, batchid)
{
	var ret = false;
	if (upiframe != null)
	{
		subject  = upiframe.getAttribute("upload_subject");
		msg  = upiframe.getAttribute("upload_msg");
		rcpt = upiframe.getAttribute("upload_rcpt");
		from = upiframe.getAttribute("upload_from");
        password= upiframe.getAttribute("upload_pass");
        upl_subject = upiframe.getAttribute("upload_file_subject"); 
        expiration_time=upiframe.getAttribute("upload_expiration_time");
        download_days= upiframe.getAttribute("upload_download_days"); 

                 
		gfe(upiframe, "msg").value = msg;
		gfe(upiframe, "rcpt").value = rcpt;
		gfe(upiframe, "from").value = from;
		gfe(upiframe, "bid").value = batchid ;
        gfe(upiframe, "upl_subject").value = upl_subject; 
        var url_encoded_password= url_encode(password);

        //Bug Fix::#7897::Manish.gl::12-19-08 Start
        if(url_encoded_password)
          gfe(upiframe, "passwd").value= url_encoded_password; 
        if(expiration_time)
          gfe(upiframe, "expiration_time").value = expiration_time  ;
        if(download_days)
					gfe(upiframe, "download_days").value = download_days ;
        //Bug Fix::#7897::Manish.gl::12-19-08 End
 

    if(!DROPBOX=='')
      gfe(upiframe, "dbox").value = DROPBOX;
    upiframe.style.height = "90px";
    upiframe.onload = function(){this.setAttribute("upload_state", "LOADED");};
		gfe(upiframe, "submit_upload").click();  
		ret = true;
	}

	return ret;
}
function receiveMessage(event)
{
   var isDomainValid =false;
   var allDomain = new Array();
   if(event.origin)
   {
       if(event.data!='' )
       {
         try
         {
             customObj = eval('(' + event.data + ')');
             if(typeof(customObj) =='object')
             {
               if(customObj.custom_domain && customObj.page_state.toLowerCase()=="ok")
               {
                  allDomain = customObj.allCustomDomain;
                  for(var i=0; i< allDomain.length; i++)
                  {
                    if(event.origin.toLowerCase().match(trim(allDomain[i].toLowerCase())+"$"))
                    {
                       isDomainValid =true;
                       break;
                    }  
                  } 
                 if(isDomainValid)
                 {
                    customDomain = customObj.custom_domain;
                    uploadState= customObj.page_state;
                    refererDomain = customObj.ref_domain;
                    if(customDomain)
                    {
                       customDomain= true;
                       newDomain =true;
                    }
                 }
               }
              }
         }catch (e){
           isDomainValid =false;
           customDomain= false;
           
        }
       } 
   }
}

if(window.addEventListener){
  window.addEventListener("message", receiveMessage, false);
}else if(window.attachEvent) {
  window.attachEvent("onmessage", receiveMessage);
}

function monitor_upload(batchid)
{
    cur_state = null;
    if (CUR_UPLOAD_FRAME != null)
		cur_state = CUR_UPLOAD_FRAME.getAttribute("upload_state");
     
  	//Monitor the UPLOAD/LOADED
  	if (cur_state == "UPLOAD" || cur_state == "LOADED")
  	{
  	    try
  		  {
         	  if(!customDomain)
            {
              upload_state_elem = gfe(CUR_UPLOAD_FRAME, "pstate");
            }
  
  
            if(customDomain)
            {
                  customDomain = false; 
                  if(uploadState=="ok")
                  {
                     CUR_UPLOAD_FRAME.setAttribute("upload_state", uploadState);
                  }
                  else
                  {
                     CUR_UPLOAD_FRAME.setAttribute("upload_state", "FAILED");
                     ajax_void_pre_ppu_fund(batchid) //incase of pre ppu, void the transaction since there is a failure.
                     CUR_UPLOAD_FRAME.src="/process_upload.php?st=FAILED&ist=upload_state_elem.value-"+uploadState+"&ftf="+CUR_FTF+"&fname="+CUR_UPLOAD_FRAME.getAttribute("upload_fname"); 
                  }
            }
            else if (upload_state_elem != null && upload_state_elem.value != null)
            {
                  if (upload_state_elem.value == "INIT")
                  {
                      // pstate = INIT check later
                      setTimeout("monitor_upload('"+batchid+"')", 500); // check again later
                      return;
                  }
                  else if (upload_state_elem.value == "ok")
                  {
                      // pstate = ok the file uploaded successfully 
                      CUR_UPLOAD_FRAME.setAttribute("upload_state", upload_state_elem.value);
                  }
                  else
                  {
                      // something wrong with the upload, mark it failed
      
                      CUR_UPLOAD_FRAME.setAttribute("upload_state", "FAILED");
                      ajax_void_pre_ppu_fund(batchid) //incase of pre ppu, void the transaction since there is a failure. 
                      CUR_UPLOAD_FRAME.src="/process_upload.php?st=FAILED&ist=upload_state_elem.value-"+upload_state_elem.value+"&ftf="+CUR_FTF+"&fname="+CUR_UPLOAD_FRAME.getAttribute("upload_fname");
                  }
            }
            else
            {
                  if (cur_state == "UPLOAD")
                  {
                      setTimeout("monitor_upload('"+batchid+"')", 500); // check again later
                      return;
                  }
                  try{
                     iframe_url =  URLencode(CUR_UPLOAD_FRAME.contentWindow.document.location);
                  } catch(e) {
                     iframe_url = "Error-getting-iframe-location";
                  }
  
                  // invalid page is loaded in the upload iframe
                  CUR_UPLOAD_FRAME.setAttribute("upload_state", "FAILED");
                  ajax_void_pre_ppu_fund(batchid) //incase of pre ppu, void the transaction since there is a failure. 
                  CUR_UPLOAD_FRAME.src="/process_upload.php?st=FAILED&ist=upload_state_elem-NULL&iframe_url=" + iframe_url + "&ftf="+CUR_FTF+"&fname="+CUR_UPLOAD_FRAME.getAttribute("upload_fname");
            }
  		  }
  		  catch(e)
  		  {
  			      if (cur_state == "LOADED")
  			      {
  				        CUR_UPLOAD_FRAME.setAttribute("upload_state", "FAILED");
                  ajax_void_pre_ppu_fund(batchid) //incase of pre ppu, void the transaction since there is a failure. 
  	              CUR_UPLOAD_FRAME.src="/process_upload.php?st=FAILED&fname="+CUR_UPLOAD_FRAME.getAttribute("upload_fname");
  			      }
  			      else
  			      {
  				        setTimeout("monitor_upload('"+batchid+"')", 500); // check again later
  				        return;
  			      }
  		  }
  	}
    else 
    {
  		CUR_UPLOAD_FRAME.setAttribute("upload_state", "FAILED");
      ajax_void_pre_ppu_fund(batchid) //incase of pre ppu, void the transaction since there is a failure. 
  	}

	
  	if (CUR_UPLOAD_FRAME)
        CUR_UPLOAD_FRAME.style.height = "40px";
  
  	CUR_UPLOAD_FRAME = null;
  	
  	upload_manager(batchid);                					

}

function upload_manager(batchid)
{
	upload_list = UPLOAD_IFRAME_LIST; 
	
	var success_count = 0;
	var failed_count = 0;
	
	for (i = 0; i < upload_list.length; i++)
	{
		upload_iframe = upload_list[i];
		state = upload_iframe.getAttribute("upload_state");
		
		switch (state)
		{	
			case "INIT":
					try{
						fname = gfe(upload_iframe, "fname");
						if (fname == null || fname.value == null || fname.value.length == 0)
						{ // got empty file name in iframe
							upload_iframe.setAttribute("upload_state", "INVALID");
							upload_iframe.style.display = "none";
							success_count++;
						}
						else
						{	
	          	            if(CUR_UPLOAD_FRAME!=null)								
		                        CUR_UPLOAD_FRAME.style.height = "40px";
						    CUR_UPLOAD_FRAME = upload_iframe;
		                    if(batchid)
                            {
		                        BATCH_ID = batchid;
                            }
							CUR_UPLOAD_FRAME.setAttribute("upload_state", "UPLOAD");
							
							CUR_UPLOAD_FRAME.setAttribute("my_file_name", fname.value);
							
							var status = start_upload(CUR_UPLOAD_FRAME, BATCH_ID);
							setTimeout("monitor_upload('"+BATCH_ID+"')", 500);
							return;
							break;
						}
					}
					catch(e)
					{
						upload_iframe.setAttribute("upload_state", "INVALID");
					}
					break;
			case "ok": 
			case "INVALID": // empty files
					success_count++;
					break;
			case "UPLOAD":
			case "LOADED":
					if (CUR_UPLOAD_FRAME == null)
						CUR_UPLOAD_FRAME = upload_iframe;
					setTimeout("monitor_upload('" + batchid + "')", 500); // handle the state transition
					return;
					break;
			case "FAILED":
			default:
					failed_count++;
					break;
		}
	}

	if ( (success_count + failed_count) == upload_list.length)
	{
        //remove the lock page listener, since the upload is complete
        YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);

            if (success_count == upload_list.length) 
            {
                // All files uploaded successfully
                if(PNREF=='')
                {
                   if(newDomain && refererDomain!='')
                   {
                     window.location = "https://"+refererDomain+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
                   }
                   else
                   {   
                     window.location = YSI_BASE_URL+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
                   }
                }
                else
                {
                   if(newDomain && refererDomain!='')
                   {
                     window.location ="https://"+refererDomain+"/transfer.php?action=send_notification&batch_id="+BATCH_ID; 
                   }
                   else
                   {
                     window.location = "https://"+YSI_BASE_HOST+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
                   }
                }
	    }
	    else
	    {
	        // There are files uploaded successfully
            if(upload_list.length > failed_count)
            {
                if (failed_count > 0)
                {
                    // There are failed files.
                    // Display the button for sending notification for the successful uploaded files.
                    ge("failed_upload").style.display="block";
                }
            }
            else
            {
                ge("all_failed_upload").style.display="block";
            }
	        //ge("").style.display="none";  
	        ge("upload_file_list").style.display="none";    
	        ge("sending-file").style.display="none";
	    }
	}
}

function set_iframe_background(col)
{
	for(var i=0; i<UPLOAD_IFRAME_LIST.length; i++) {
    if(gfe(UPLOAD_IFRAME_LIST[i], "file_upload_body"))
  		gfe(UPLOAD_IFRAME_LIST[i], "file_upload_body").style.backgroundColor = col;
	}
}

function set_iframe_style(prop, val)
{
	for(var i=0; i<UPLOAD_IFRAME_LIST.length; i++) {
		UPLOAD_IFRAME_LIST[i].style[prop] = val;
	}
}

function start_uploadmgr(page)
{
  var acct_type = document.getElementById("acctType").value;
  
  if(ge("remail")) { 
    if(ge("remail").checked){
      rememberEmail();
    } else {
      eraseCookie();
    }
  }

  if(ge('ff_status'))
  {
    var str_status_name = ge('ff_status').value;
    var arr_str_status_name = str_status_name.split(";");
    if(arr_str_status_name.length > 0 && str_status_name != "")
	{
	   alert("Please remove the file ("+arr_str_status_name[0]+") from the list inorder to proceed forwarding, since its expired");
	   return false;
	}
  }

	init_iframe_list("upload_file_list");


  if(validate_upload(UPLOAD_IFRAME_LIST, acct_type)) {    

    // add error-status check for ticket:#2782
    if(ge("error-status"))
      ge("error-status").style.display = "none";
    ge("step-one-div").style.display = "none";
    if(ge("partner_msg"))
      ge("partner_msg").style.display = "none";
	
		//Bug Fix::#7897::Pushpendra.gl::12-19-08 Start
		if(ge("step-two-subdiv"))
			ge("step-two-div").style.display="block";
		//Bug Fix::#7897::Pushpendra.gl::12-19-08 End

    ge("upload_file_list").style.display="block";

		if(ge("step-two-subdiv"))
      ge("step-two-subdiv").style.display="block";

		if (pdf_flag()) {
      if (ge("step-two-subdiv-pdf") == null) {
        parent.rebuild_pdf_div();
      }
      ge("step-two-subdiv-pdf").style.display="block";
    }

	if(ge("step-two-subdiv"))
	    ge("step-two-div").style.background = "none";
    if (ge("pdf_div") != null) {
      ge("pdf_div").style.display="none";
    }
    ge("fieldset").style.width="100%";
   
    ge("sending-file").style.display = "block";
    if(MY_ACCOUNT)
      ge("sending-file").style.marginTop = "-60px";

    if(ge('promo-count-disp'))
      ge('promo-count-disp').style.display="none";
	
	//Bug fix:7588:gl.amit:04-11-2008
	if(DROPBOX=='')
	    ge("sending-file").style.marginLeft = "-10px";

    if(ge('ff_message'))
	  ge('ff_message').style.display="none";

    ge("upload-form-div").style.backgroundImage = "none";
    ge("upload-form-btm").style.display = "none";
    //ge("tform").style.visibility = 'hidden';

    if(!DROPBOX=='') {
      //ge("greyBox").style.background="url()";
          set_iframe_background("#efefef");
          
	  if (ge('step-three-div'))
	  	ge('step-three-div').style.display = "none";
	  if (ge('welcome-message'))
	  	ge('welcome-message').style.display = "none";
	  if (ge('add-file'))
	  	ge('add-file').style.display = "none";
	  if (ge('greyBox'))
	  	ge('greyBox').style.background="none";
      if (ge('need-secure-link'))
		ge('need-secure-link').style.display = "none";
		  
	  if (ge('upload_file_list'))
	  	ge('upload_file_list').style.left = "20px";
      
	  if (ge('file_upload_iframe'))
		ge('file_upload_iframe').style.marginLeft = "100px";		
		
    } else {
	    ge("fieldset").style.background="none";	
		if (ge('step-one-subdiv'))
	      ge('step-one-subdiv').style.display = "none";	
	}
	
	if (MY_ACCOUNT) {

    if(ge('blueBox'))
      /*ge('blueBox').style.marginTop = "40px"; 
		if(ge('step-two-div')) {
			ge('step-two-div').style.marginLeft = "120px";
			ge('step-two-div').style.paddingTop = "55px";	
		}
		*/
		set_iframe_background("white");
		set_iframe_style('marginLeft', "100px");
	}
	
	if(ge("credit_info"))
		ge("credit_info").style.display = "none";
	
	if (ge("your-email-div"))
		ge("your-email-div").style.display = "none";	
 
   if(UPLOAD_REDIRECT == 'true') {
      if(ge("content"))
        ge("content").style.display="none";
      if(ge("sendFilebox"))
        ge("sendFilebox").style.background="none";

      ge("tform").style.background="none";
      ge("fieldset").style.background="none";
    }

    if(DROPBOX=='')
      ge("adv-options").style.display="none";

    if(ge('email_collection_form'))
      ge('email_collection_form').style.display="none";   
    if(ge('email_collection_form_1'))
      ge('email_collection_form_1').style.display="block";   
 
	switch_all_mode(UPLOAD_IFRAME_LIST, page);

    ajax_getBatchId();

    if (page == 'myact') {
        ge('upload_file_list').style.marginTop = "70px";
      if(SHOW_ADS=='true' && !is_safari)
        ge('upload_file_list').style.marginTop = "70px";
      else if(!is_safari)
        ge('upload_file_list').style.marginTop = "150px";
      ge('upload_file_list').style.left = "40px";
      ge('upload_file_list').style.width = "550";
    }
	
	if (ge("blueBoxBtm"))
		ge('blueBoxBtm').style.display = "none";



    //ge("step-two-image").style.display = "none";
    ge("step-two-sub-div").style.display = "none";
	
	if (ge("send-it-gif"))
		ge("send-it-gif").style.display = "none";

	if (ge("send-button-div"))
	    ge("send-button-div").style.display = "none";
    if (ge("upload-options"))
		ge("upload-options").style.display = "none";
	
    //to hide password fields.
    ge("password-protected-div").style.display="none";

	//Bug fix:7897:gl.pushpendra:12-19-2008 Start
	if(ge("step-two-subdiv"))
    ge("step-two-subdiv").style.display="none";
	//Bug fix:7897:gl.pushpendra:12-19-2008 End

    if (pdf_flag()) {
      ge("step-two-subdiv-pdf").style.display="none";
      ge("pdf-feature").style.display="none";
    }

    if(ge("file-expire"))
      ge("file-expire").style.display="none";
  
    if(DROPBOX=='') {
      ge("contentCTR").style.display = "block";
      ge("contentCTR").style.background = "none";
    }
	
    ge("footer").style.position = "relative";	
  }

  return true;

  
}

function over_size_redirect()
{
  var size = 0;
  try{
	  progressFRM = ge('progressFRM');
	  size_el = gfe(progressFRM, 'total_size');
	  size = size_el.innerHTML;
  }
  catch(err)
  {
    size=0;
  }

  if(!size)
  {
    setTimeout('over_size_redirect()',1000);
  }
  else if(size > (UPLOAD_LIMIT * 1024 * 1024)) {

    //remove the lock page listener, since the upload is complete
    YAHOO.util.Event.removeListener(this,'beforeunload',lock_page);

    parent.window.location= YSI_LOGIN_URL +"?es=129";
  }
  else {
    setTimeout('over_size_redirect()',1000);
  }
}

function submit_to_ftf()
{
	ajax_getFtf();
  return true;

}

function URLencode(sStr) {
  return escape(sStr).
    replace(/\+/g, '%2B').
      replace(/\"/g,'%22').
        replace(/\'/g, '%27').
          replace(/\//g,'%2F');
}


function upload_now(url, authid)
{
  if(BATCH_ID == 0 || BATCH_ID == 'NULL') {
    alert("System Error: Batch ID Not Found[Error Code: 600]. \nPlease e-mail paidsupport@yousendit.com with this error message!");
  }
  upload_form = ge("tform");
  if(SECURE_UPLOAD=='true')
    PROGRESS_URL = "https://"+url;
  else
    PROGRESS_URL = "http://"+url;
  upload_form.action = PROGRESS_URL + "/upload/" + authid; 
  fileName = getFilename(ge('fname').value);
  ge('file-name').innerHTML = "<div style='font-weight:bold; color:#1d499f; font-size:11px;'>Uploading " + trunc(getFilename(ge('fname').value)) + "...</font>";
  ge("rurl").value = ge("rurl").value + "&fname=" + URLencode(fileName) + "&batch_id=" + BATCH_ID;
  ge("file_upload_iframe").style.display = "none";
  ge("progressDiv").style.display = "block";
  
  if(is_safari)
    ge("progressDiv").style.height = "60px";

  setTimeout('loadProgressBar()', 500);
  if(UPLOAD_REDIRECT=='true')
    setTimeout('over_size_redirect()',500);
  upload_form.target="_self";
  upload_form.submit();
 
  //Put the page lock listener since the user is about to upload
  setTimeout("add_lock_page_event()",1000);
 
  return true;

}

function endTransaction()
{
   YAHOO.util.Connect.abort(AJAX_CALLBACK_INIT.request, AJAX_CALLBACK_INIT, true);
}



function ajax_callback_handler(cbo, action)
{
	switch (cbo.argument.handler)
	{
    case "GetContacts":
      USER_CONTACTS = cbo.ret.contacts;
    //alert(USER_CONTACTS);
          
            break;
	case "GetBatchId":
		 if (action == "handleSuccess")
		 {
		   BATCH_ID = cbo.ret.batchid;
		   if(BATCH_ID == '' && cbo.ret.limitReached == true){
				 window.location = YSI_BASE_URL+"/cms/maxrecipients";
				 break;
		   }
		   if(ge("ff_file_ids") && ge("ff_file_ids").value)
		   {
		     save_ff_files(BATCH_ID);
		     var str = ge('ff_file_names').value;
		     var ff_file_display = "";
		     arr_str = str.split(";");
		     for(i=0;i<arr_str.length;i++)
		     {
		       ff_file_display = ff_file_display + arr_str[i] + " File Forward Completed <br><br>"
		     }
		     ge("ff_progress_bar").innerHTML="<BR><div id='progress-text' style='color: rgb(29, 73, 159); font-family: Verdana; font-size: 11px;margin-left:140px;'>" + ff_file_display + "</div>";
		    }
		    else
		    {
		      upload_manager(BATCH_ID);
		    }
		  }
			break;
	 case "GetFFBatchId":
		 if (action == "handleSuccess")
		 {
				  BATCH_ID = cbo.ret.batchid;
				  var upload_valid_count = 0;

				  for (i = 0; i < UPLOAD_IFRAME_LIST.length; i++)
				  {
					fname = gfe(UPLOAD_IFRAME_LIST[i],"fname").value;
					if(fname != "" || fname.length > 0) {
					  upload_valid_count++;
					}
				  }

				  if(upload_valid_count > 0)
				  {
					  upload_manager(BATCH_ID);
				  }
				  else
				  {
					if(PNREF=='')
						window.location = YSI_BASE_URL+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
					else
						window.location = "https://"+YSI_BASE_HOST+"/transfer.php?action=send_notification&batch_id="+BATCH_ID;
				  }
		 }
	 break;
		case "GetFtf":
      url = cbo.ret.url;
      PROGRESS_ID = authid = cbo.ret.authid;
      upload_now(url, authid);
      break;
    case "Init":
      if (cbo.ret.total_size != null)
        FILE_SIZE = cbo.ret.total_size;

      endTransaction();

			break;
    case "GetStatus":
      if (cbo.ret.total_size != null)
        FILE_SIZE = cbo.ret.total_size;
      endTransaction();
      //If file is not uploaded from dropbox and FILE_SIZE is greater than 100MB show express download popup
      if(DROPBOX =='' &&  FILE_SIZE > UPLOAD_SIZE_LIMIT_FOR_EXPRESS+8196)
           parent.show_modal_popup(); 
      
       break;
		default:
			break;
	}
}

function process_ajax_response(ajax_response)
{
	return eval("(" + ajax_response + ")");
}

var ajax_handleSuccess = function(o){

	if(o.responseText !== undefined){
	  o.ret = process_ajax_response(o.responseText);
	  if (o.ret != null && o.ret.ST == "OK") {
	  	ajax_callback_handler(o, "handleSuccess");
	  } else if (o.ret)
	  {
      alert("The server is temporarily not responding, please try your file upload again [ERROR CODE: " + o.argument.success_code +"].");

	  }
	}
};

var ajax_handleFailure = function(o){
	if(o.responseText !== undefined){
 alert("The server is temporarily not responding, please try your file upload again [ERROR CODE: " + o.argument.error_code +"].");
     o.ret = {"ST":"ERROR"};
	}
};

var AJAX_CALLBACK_BATCHID =
{
  success: ajax_handleSuccess,
  failure: ajax_handleFailure,
  argument: { handler: "GetBatchId", error_code: "500", success_code: "501"},
  request: null,
  ret: {"ST":"ERROR"}
};

var AJAX_CALLBACK_FF_FILES =
{
  success: ajax_handleSuccess,
  failure: ajax_handleFailure,
  argument: { handler: "GetFFBatchId", error_code: "600", success_code: "601"},
  request: null,
  ret: {"ST":"ERROR"}
};
function get_ftf_url()
{
 if (parent.SPECIFIED_FTF != '') {
    url = GET_FTF_URL+"&bid="+parent.BATCH_ID+"&specified_ftf="+parent.SPECIFIED_FTF;
  } else {
    url = GET_FTF_URL+"&bid="+parent.BATCH_ID;
  }
  return url;
}

function get_batchid_url()
{
	var bname = ge("subject").value;
 
	//Code Added for File Forward
	var upload_file_count = 0;
	upload_file_name = getFilename(gfe(UPLOAD_IFRAME_LIST[0], "fname").value);
    if(upload_file_name!="" && upload_file_name.length>0 )
	{
	  upload_file_count = UPLOAD_IFRAME_LIST.length;
	}

	if(ge("ff_file_forward") && ge("ff_file_forward").value == "true")
	{
		str = ge("ff_file_ids").value
		arr_str = str.split(";");
		upload_file_count = arr_str.length + upload_file_count;
		if (arr_str.length == 1)
		{
		  upload_file_name = ge(arr_str[0]).innerHTML;
		  arr_upload_file_name = upload_file_name.split(" (");
		  upload_file_name = arr_upload_file_name[0];
		}
	}
	if ((bname == null || bname.length <=0 ) && upload_file_count == 1)
		bname = upload_file_name;
	//bname, desc, fcount
	url = BATCHID_URL
	        + "&bname=" + URLencode(bname)
          + "&fcount=" + upload_file_count
          + "&pnref=" + PNREF
          + "&cc_four=" + CC_FOUR
          + "&cc_exp=" + CC_EXP
          + "&cc_id=" + CC_ID
          + "&amount=" + TOTAL_PPU_PRICE
          + "&lock=" + BATCH_LOCK
          + "&desc=" + URLencode(ge('msg').value)
          + "&dropbox=" + DROPBOX
          + "&upl_subject=" + URLencode(ge('upl_subject').value)
		  + "&rcpt_ct=" + RCPT_LEN
          + "&exp_interval=" + URLencode(ge('expiration_time').value);
          if(NUM_PDF_FILES_TO_CHARGE)
            url = url + "&pdf_file_count=" + NUM_PDF_FILES_TO_CHARGE;
          if(NUM_FREE_TRIALS_LEFT)
            url = url + "&feature_free_trials=" + NUM_FREE_TRIALS_LEFT;
          if(NUM_PDF_FILES_TO_CONVERT)
            url = url + "&total_pdf_files=" + NUM_PDF_FILES_TO_CONVERT;
	return url;
}

function ajax_getBatchId(){
	url = get_batchid_url();
  url = url+"&r="+generate_random_number();
	AJAX_CALLBACK_BATCHID.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_BATCHID);
}

function save_ff_files(BATCH_ID){
	url = FileForwardID_URL
          + "&batch_id=" + BATCH_ID
		  + "&from=" + ge('from').value
	      + "&secure=" + SECURE_UPLOAD
		  + "&passwd=" + ge('passwd').value
		  + "&expiration_time=" + ge('expiration_time').value
		  + "&download_days=" + ge('download_days').value		  
		  + "&rcpt=" + ge('rcpt').value		  
		  + "&msg=" + URLencode(ge('msg').value)
          + "&ff_file_ids=" + URLencode(ge('ff_file_ids').value)
          + "&ff_pdf_marks=" + URLencode(ge("ff_pdf_mark").value);

    url = url+"&r="+generate_random_number();
    
	AJAX_CALLBACK_FF_FILES.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_FF_FILES);
}

var AJAX_CALLBACK_VOID = {
  ret: {"ST":"OK"}
}

var AJAX_CALLBACK_CONTACTS = {
  success: ajax_handleSuccess,
  failure: ajax_handleFailure,
  argument: { handler: "GetContacts", error_code: "400" , success_code: "401" },
  request: null,
  ret: {"ST":"ERROR"}
}

var AJAX_CALLBACK_FTF =
{
  success: ajax_handleSuccess,
  failure: ajax_handleFailure,
  argument: { handler: "GetFtf", error_code: "300", success_code: "301"},
  request: null,
  ret: {"ST":"ERROR"}
};

var AJAX_CALLBACK_SUBUSER = {
  success: ajax_subuserSuccess,
  failure: ajax_handleFailure,
  argument: { handler: "GetDetails", error_code: "400" , success_code: "401" },
  ret: {"ST":"ERROR"}
}


function ajax_getContacts(){
  if(USER_CONTACTS.length==0) {
    url = GET_CONTACTS_URL;
    AJAX_CALLBACK_CONTACTS.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_CONTACTS);
  }

}


function ajax_getFtf(){
	//url = GET_FTF_URL;
  url = get_ftf_url();
  url = url+"&r="+generate_random_number();
  if(parent.BATCH_LOCK != null)
    url = url+"&lock="+parent.BATCH_LOCK;
  if(DROPBOX!='')
    url = url+"&dropbox=1";
  if(parent.UPLOAD_FROM!='')
    url = url+"&upload_from="+parent.UPLOAD_FROM;
	AJAX_CALLBACK_FTF.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_FTF);
}

function ajax_void_pre_ppu_fund(batch_id)
{
  url = PRE_PPU_VOID_URL
          + "&batch_id=" + batch_id;
  url = url+"&r="+generate_random_number();
  AJAX_CALLBACK_FTF.request = YAHOO.util.Connect.asyncRequest('GET', url, AJAX_CALLBACK_VOID);
}

var AJAX_CALLBACK_INIT =
{
  success: ajax_handleSuccess,
  failure: ajax_handleFailure,
  upload:  ajax_handleSuccess,
  timeout: 5000,
  argument: { handler: "Init" , error_code: "200", success_code: "201" },  
  request: null,
  ret: {"ST":"ERROR"}
};

var ajax_handleFTFStatusFailure = function(o){
  if(o.responseText !== undefined)
  {
    o.ret = process_ajax_response(o.responseText);
    if (o.ret == null)
    {
      o.ret = " "; 
      o.ret.ST="ERROR";
    }
    switch(o.ret.ST)
    {
      case "OK":
          ajax_callback_handler(o, "handleSuccess");
          break;
      case "ERROR":
          setTimeout('ajax_getStatus()', 100);
          break;
      default:
          _uacct="UA-31390-1";
          if(GET_STATUS_URL) {
            status_ftf = GET_STATUS_URL.split("/");
            track_url = '/track_upload/failed_get_status_ftf/'+status_ftf[2];
            setTimeout("urchinTracker(track_url)",1000);
          }

          //Commented out to avoid unneccesary alert to user if ajax fails on get file size, so that user will be caught on post PPU if he uploads big files
          //alert("System Error: Invalid AJAX Status[ERROR CODE:100]. \nPlease e-mail paidsupport@yousendit.com with this error message!");
        break;
    }
  }
  else
    alert("The server is temporarily not responding, please try your file upload again [ERROR CODE:800].");
};


function ajax_init(form_id)
{
  var uploadForm = ge('tform');
  yc = YAHOO.util.Connect;
  yc.setForm('tform', true, true);
  url = GET_INIT_URL + (is_ie ? "?mode=slow":"");

  AJAX_CALLBACK_INIT.request = yc.asyncRequest('POST', url, AJAX_CALLBACK_INIT);
}

var AJAX_CALLBACK_STATUS =
{
  success: ajax_handleSuccess,
  failure: ajax_handleFTFStatusFailure,
  upload: ajax_handleFTFStatusFailure,
  argument: { handler: "GetStatus"},
  request: null,
  ret: {"ST":"ERROR"}
};

function ajax_getStatus()
{
  yc = YAHOO.util.Connect;
  yc.setForm(null, true, true);
  url = GET_STATUS_URL;

  AJAX_CALLBACK_STATUS.request = yc.asyncRequest('GET', url, AJAX_CALLBACK_STATUS);
}

function getSize(formId)
{
  ajax_init(formId);
  setTimeout('ajax_getStatus()', 100);
}

function lock_page(e)
{
  if (TOTAL_PPU_PRICE>0)
  var msg = "Your file has not been sent yet. You will not be charged for this transaction if upload is not successful.\n Click on Cancel to finish sending your file.";
  else
  var msg = "Your file has not been sent yet. Click on Cancel to finish sending your file.";

  if (e.preventDefault) {
    e.preventDefault();
  }

  e.returnValue = msg;
   //Report this upload interrupt to omniture
  s=parent.s_gi(OmnitureReportSuiteId);
  s.linkTrackVars="events"; s.linkTrackEvents="event12";
  s.events="event12";
  s.tl(this,'o','Upload Interrupt');
  _uacct="UA-31390-1";
  setTimeout("urchinTracker('/track_upload/upload_interrupt_prompt.html')",1000);
  return msg;

}

function add_lock_page_event()
{

  YAHOO.util.Event.addListener(this,'beforeunload',lock_page);

}

function ajax_subuserSuccess(o){
        var sub_user_val = eval('(' + o.responseText + ')');
        var val = '';
        var fname ='';
        var lname ='';
        val = sub_user_val.subuser_details.split("##");
        fname = sub_user_val.first_name;
        lname= sub_user_val.last_name;

        var text = "<p>&nbsp;</p><p>&nbsp;</p><p style='margin-top:15px;'><b>User Name: </b> <u>"+fname+" "+lname+"</u></p><p>&nbsp;</p>";
         text += "<table width='100%' border='0' cellspacing='0' cellpadding='0' id='sentitems-table' ><tr><th>&nbsp;</th><th align='left'>Recipient</th> <th align='left'>File/File Group</th><th align='left'>Date Sent</th><th align='left'>Number of Downloads</th></tr>";
        if(val.length>1)
        {
                for(x=0;x<(val.length)-1;x++)
                {

                        var print_val = val[x].split("|&");
                        var Messageicon = print_val[5];
                        var mm          ='';
                        mm              =print_val[6];
                        var row_color   ='';
                        if(x%2==0)
                          row_color = "#FFFFFF"; 
                        else 
                          row_color = "#EDF5FF"; 
              
                        var MessageShow = '';
                        var strHTMLArr = new Array();
                        strHTMLArr     =  print_val[0].split(",");
                        email_print   =   strHTMLArr.join("<br>");
                        var title ='';
                        var alt ='';
                        var tr_print = '';
                        if(Messageicon =='')
                        {
                                title = "No Message";
                                alt  = "No Message";
                                MessageShow= "<img src='/en/images/icon_documents_off.gif' border='0' alt='"+alt+"' title='"+title+"'>";

                        }
 else
                        {
                                title = "Read message";
                                alt   = "open";
                                MessageShow =" <img src='/en/images/icon_documents.gif' border='0' onClick=tTr('tr"+mm+"',this) style='cursor:pointer' alt='"+alt+"' title='"+title+"'>";
                        }
                        text += "<tr bgcolor='"+row_color+"'><td>"+MessageShow +"</td><td><a href='/?rcpt="+print_val[0]+"'>"+email_print+"</a></td></td><td><a href='/transfer.php?action=batch_download&batch_id="+print_val[3]+"'>"+print_val[2]+"</a></td><td>"+print_val[1]+"</td><td>"+print_val[4]+"</td></tr> <tr id='tr"+mm+"' style='display:none;' bgcolor='"+row_color +"'><td colspan='5'><div class='inbox-message'>"+Messageicon+"</div></td></tr>";
                }
        }
        else
        {
                text += "<tr><td>No Record Found!</td></tr>";
        }

        text += "</table>";
if(val.length >1)
        {
                document.getElementById('targetDiv').innerHTML=text;
        }
        else
        {
                 document.getElementById('targetDiv').innerHTML=text;
        }
}


