//******************************************
//***** COMMON FUNCTIONS           *********
//******************************************

//Standard new window
function newWindow(mypage,w,h)
{   
   h = screen.height * 0.85;
   w = screen.width * 0.95;


   winprops = "scrollbars=yes,menubar=no,locationbar=no,toolbar=no,resizable=yes,dependent=yes,alwaysRaised=yes,hotkeys=no,directories=no,status=yes," + ' height=' + h +',width=' + w;

   win = window.open(mypage,"theMailMonster",winprops);

}

function newWindowMedium(mypage,w,h)
{   
   h = 300;
   w = 300;


   winprops = "scrollbars=yes,menubar=no,locationbar=no,toolbar=no,resizable=no,dependent=yes,alwaysRaised=yes,hotkeys=no,directories=no,status=no," + ' height=' + h +',width=' + w;

   win = window.open(mypage,"theMailMonster",winprops);

}


//Navigate function
function navigateTo(navLocation) {
        window.location = navLocation;
}

function limitText(limitField, limitCount, limitNum) {           
       limitNum = limitNum.split(";",1);

	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}

        EbayCheckKeyPressed(limitField.value);
}


function clearAll(){

  var texts=document.getElementsByTagName('input')
  for (var i_tem = 0; i_tem < texts.length; i_tem++)
  if (texts[i_tem].type=='text')
  texts[i_tem].value=''

  document.FORM_PROMO.recip_message.value=''
  document.getElementById('optionsExtra').options[0].selected=true;
  var div_ref = document.all("uploadFile");
  div_ref.style.visibility = "hidden";

}


//Redirect Submission of forms
function redirectOutput(myForm)
{   
    // Browser Specific
    if(navigator.appName == "Netscape")
    {
       h = screen.height * 0.80;
       w = screen.width * 0.90;
    }
    else
    {
       h = screen.height * 0.80;
       w = screen.width * 0.90;
    }


    winprops = "scrollbars=yes,menubar=no,locationbar=no,toolbar=no,resizable=yes,dependent=yes,alwaysRaised=yes,hotkeys=no,directories=no,status=yes," + 'height=' + h +',width=' + w;

   win = window.open('redirectpage.html','Popup_Window',winprops);
   myForm.target = 'Popup_Window';
}


function send_submitForm_PROMO(type)
{
   if (type == 'preview')
   {

      redirectOutput(document.FORM_PROMO)
      document.FORM_PROMO.action = "loading.php?page=sendLetterPreview&country=" + document.FORM_PROMO.country.value;
      document.FORM_PROMO.submit()
   }
   else
   {
      redirectOutput(document.FORM_PROMO)

      sKeywords = BuildKeywords(document.FORM_PROMO.recip_message.value);

      sKeywords = "&uId1=" + randomString() + "&uId2=" + randomString() + "&uId3=" + randomString() + "&uId4=" + randomString() + "&Keywords=" + sKeywords;

      document.FORM_PROMO.action = "select.php?page=loading&country=" + document.FORM_PROMO.country.value + sKeywords;

      document.FORM_PROMO.submit()
   }
}


function menuContent(option) 
{ 

  if (option==0) { 
    frames['menu'].location.href="welcome.html"; 
  } 
  if (option==1) { 
    frames['menu'].location.href="free.html"; 
  } 
  if (option==2) { 
    frames['menu'].location.href="security.html"; 
  } 
  if (option==3) { 
    frames['menu'].location.href="features.html"; 
  } 
  if (option==4) { 
    frames['menu'].location.href="contactus.html"; 
  } 
  if (option==5) { 
    frames['menu'].location.href="terms.html"; 
  } 
  if (option==6) { 
    frames['menu'].location.href="privacy.html"; 
  } 
 

}


function tblColHand(tbl) {
        tbl.style.cursor='pointer'
}


//******************************************
//***** EXTRA OPTIONS              *********
//******************************************

function extraOptions(thisValue) 
{

  // Standard
   if (thisValue==1) 
   { 
     document.FORM_PROMO.Template_ID.value = 1;
     var div_ref = document.all("uploadFile");
     div_ref.style.visibility = "hidden"; 
   }

   // Standard
   if (thisValue==2) 
   { 
     document.FORM_PROMO.Template_ID.value = 2;
     var div_ref = document.all("uploadFile");
     alert(' Max PDF File Size: 200 KB \n Max Number of Pages: 2 \n\n NOTE: If PDF Files are attached, the Letter will be printed in B/W  ');
     div_ref.style.visibility = "visible"; 
   }

   if (thisValue==3) 
   { 
     document.FORM_PROMO.Template_ID.value = 3;
     var div_ref = document.all("uploadFile");
     alert(' Valid File Format: *.jpg \n Max File Size: 50 KB ');
     div_ref.style.visibility = "visible";
   }

   
}


//******************************************
//***** THEMES                     *********
//******************************************

// Extra Option for THEMES
function extraOptionsThemes(thisValue)
{
   if (thisValue==1) 
   { 
     document.FORM_PROMO.Template_ID.value = 1;
     var div_ref = document.all("uploadFile");
     div_ref.style.visibility = "hidden"; 
   }
   if (thisValue==2) 
   { 
     document.FORM_PROMO.Template_ID.value = 2;
     var div_ref = document.all("uploadFile");
     alert(' Max PDF File Size: 200 KB \n Max Number of Pages: 2 \n\n NOTE: If PDF Files are attached, the Letter will be printed in B/W  ');
     div_ref.style.visibility = "visible";
   }

}


function getImage(dirValue)
{ 

   frames['themesImage'].location.href = "themesImage.php?dir=" + dirValue;
   document.FORM_PROMO.categoryImage.value = '';

}


function setImageValue()
{
   document.FORM_PROMO.categoryImage.value = window.frames['themesImage'].document.forms['IMAGE'].elements['categoryImage'].value;
   alert('Image Saved.')
}


function printHeadingCheck()
{

    var el = document.all('print_headingChk');
    if (el.checked == false)
      document.FORM_PROMO.print_heading.value = 'N';
    else
      document.FORM_PROMO.print_heading.value = 'Y';

}

//******************************************
//***** Cookie an Toggle Functions *********
//******************************************

function toggleDiv(id,flagit) 
{
   if (flagit=="1")
   {
      if (document.layers) document.layers[''+id+''].visibility = "show"
      else if (document.all) document.all[''+id+''].style.visibility = "visible"
      else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
   }
   else
   if (flagit=="0")
   {
      if (document.layers) document.layers[''+id+''].visibility = "hide"
      else if (document.all) document.all[''+id+''].style.visibility = "hidden"
      else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"
   }
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function checkIntroCookie()
{
  introInd=getCookie('introInd')
  if (introInd!=null && introInd!="")
  {
    // Do Nothing
      toggleDiv('DIV6',0);
  }
  else 
  {
      toggleDiv('DIV6',1);
  }
}


function Set_Cookie( name, value, expires, path, domain, secure ) 
{
   // set time, it's in milliseconds
   var today = new Date();
   today.setTime( today.getTime() );

   /*
   if the expires variable is set, make the correct 
   expires time, the current script below will set 
   it for x number of days, to make it for hours, 
   delete * 24, for minutes, delete * 60 * 24
   */
   if ( expires )
   {
      expires = expires * 1000 * 60 * 60 * 24;
   }
   var expires_date = new Date( today.getTime() + (expires) );

   document.cookie = name + "=" +escape( value ) +
   ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
   ( ( path ) ? ";path=" + path : "" ) + 
   ( ( domain ) ? ";domain=" + domain : "" ) +
   ( ( secure ) ? ";secure" : "" );
}


function setIntroCookie()
{
   if(document.all.doNotShow.checked)
   {
     Set_Cookie( 'introInd', 'set', '30', '/', '', '' );
   }

   toggleDiv('DIV6',0);
}

//******************************************
//***** Set Defaults               *********
//******************************************

function SetDefaults()
{ 
   //scroll();

   // if coming from multiple recip menu then catch error   
   try
   {
       document.FORM_PROMO.recip_name.focus()
   }
   catch(err)
   {
        // nothing
   }

   frames['menu'].location.href="welcome.html";
   checkIntroCookie();

}

function SetDefaultsThemes()
{ 
   //scroll();

   // if coming from multiple recip menu then catch error   
   try
   {
       document.FORM_PROMO.recip_name.focus()
   }
   catch(err)
   {
        // nothing
   }

   frames['themesImage'].location.href = "themesImage.php?dir=birthday"
   document.FORM_PROMO.categoryImage.value = window.frames['themesImage'].document.forms['IMAGE'].elements['categoryImage'].value;


}


function SetDefaultsInternational(pageName,cID,infoMsg)
{ 

   var div_ref = document.all("uploadFile");
   div_ref.style.visibility = "hidden";

   if (cID !== "") 
   {
     document.FORM_PROMO.recip_name.focus()
   }

   if (infoMsg !== "") 
   {
     alert(infoMsg);
   }


   if (pageName == "thm") 
   {
      document.all.themesImage.src = "themesImage.php?dir=birthday"
      document.FORM_PROMO.categoryImage.value = window.frames['themesImage'].document.forms['IMAGE'].elements['categoryImage'].value;
   }
   else
   {
      checkIntroCookie();
   }
}


//******************************************
//***** Payment Fuctions           *********
//******************************************

function payPalChangeAmt(thisVal)
{
  document.PAYPAL_FORM.amount.value = thisVal;
  document.PAYPAL_FORM.item_name.value = "International Mail - $" + thisVal + "";
}+ "&uId1=" + randomString()

function submitPaypal()
{
  document.PAYPAL_FORM.paypalText.value= "       Performing Security Check. Please wait...";
  document.PAYPAL_FORM.submit();

}


function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 50;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}


function checkCreditCode()
{

  window.location = 'international.php?country=au&itnl=1&page=sta' + '&sID1=' + randomString() + randomString() + '&cID1=' + document.all.credit_code1.value + '&sID2=' + randomString() + randomString() +  '&cID2=' + document.all.credit_code2.value + '&sID3=' + randomString()  + randomString() +  '&cID3=' + document.all.credit_code3.value ;
}


function setCountry(thisVal)
{
  document.FORM_PROMO.recip_country.value = thisVal; 
  document.all.countryText.style.backgroundColor = "#008000";
  document.all.countryText.value = '  You can now send your letter';

}



function BuildKeywords(input) 
{
   var output = "";
   for (var i = 0; i < input.length; i++) 
   {
      if ((input.charCodeAt(i) == 13) && (input.charCodeAt(i + 1) == 10)) {
      i++;
      output += " ";
      } 
      else 
      {
         output += input.charAt(i);
      }
  
      // Maximum of 500 characters
      if(i > 500)
      {
         return output;
      }
     
  }

   return output;
}


//******************************************
//***** Scrolling Text             *********
//******************************************

/*
var timerId;
var counter = 0;
var msg = "Send an Online Letter from the Internet to a Postal Mailbox!!! Make Someone's day. Click on 'Themes' to send themed letters such as Birthday, Love, Friendship and many more...";
    msg = msg + ""

// Is the timer already running?
if (timerId != null)
  clearTimeout(timerId);

function pad() 
{
   var padding = "";
   // Prepend 50 spaces to the message:
   for (var n=0; n <= (-100 + msg.length); n++)
     padding += " ";
   return(padding);
}



function scroll() 
{



   newMsg = pad() + msg + " ";
   document.all.tip.value = newMsg.substring(counter, newMsg.length);
   if (counter == newMsg.length) 
   {
      counter = 0;
   }
   counter ++;
   timerId = setTimeout("scroll()", 120); 
   return true;



}
*/

//******************************************
//***** STATE VALIDATION           *********
//******************************************

function checkStreet()
{
  
     var street = document.FORM_PROMO.recip_street.value.toUpperCase();

     var numberDetected = 1;
     if(street.length > 0)
     {
         numberDetected = 0;
         for(var j=0; j<street.length; j++)
         {
              alphaa = street.charAt(j);
	      hh = alphaa.charCodeAt(0);
       
              // A number is detected
              if((hh > 46 && hh < 58))
              {
                   numberDetected++;
              }
         }
     }


     if(!numberDetected)
     {
          if(confirm("theMailMonster.com - Address Validation \n\nPlease confirm this Address: \n\n " + street + "\n\n Are you sure this is the correct Address?"))
          {
                 //nothing       
          }
          else
          {
             document.FORM_PROMO.recip_street.value= "";
             document.FORM_PROMO.recip_street.focus();

          }

     }

}



function checkState(cntry)
{
  


     var state = document.FORM_PROMO.recip_state.value.toUpperCase();
     state = state.replace(/^\s+|\s+$/g, '') ;

     if(cntry == 'au')
     {
       validateStateAU(state);  
     }
     else if(cntry == 'us')
     {
       validateStateUS(state);  
     }



}



function showStateErrorMsg(val,states,cntry)
{

   var found = 0;
   for (var i = 0; i < states.length; i++)
   {
      if(val == states[i])
        found = 1;
   }

   postcardInd  = location.href.search("postcard");

   if(parseInt(postcardInd) > 0)
       MailType = "Postcard";
   else
       MailType = "Letter";

   if (!(found))
   {
     alert("You are Sending a " + MailType + " to " + cntry + ". \n " + '"' + val + '"' + " is an Invalid State. Please re-enter.")
     document.FORM_PROMO.recip_state.value= "";
     document.FORM_PROMO.recip_state.focus();
   }

}


function openMultipleAddress()
{
   document.all['MULTI_ADDRESS'].style.visibility = 'visible';
}

function resetMultipleAddress()
{
   document.all['MULTI_ADDRESS'].style.visibility = 'hidden';
   document.all['recip_address'].value = "";
   document.all['multi_address_ind'].value = 0;
}

function confirmMultipleAddress()
{
   document.all['MULTI_ADDRESS'].style.visibility = 'hidden';
   document.all['multi_address_ind'].value = 1;
}



function CheckAddress(thisTextArea,thisValue)
{
      AdrressArray = thisValue.split("\n");

      if (AdrressArray.length > 4)
      {                             
          thisTextArea.value = AdrressArray[0] + "\n" + AdrressArray[1] + "\n" + AdrressArray[2] + "\n" +AdrressArray[3];
              
      }
}

function validateStateAU(val)
{
   var states=new Array(10)
   states[0]=""
   states[1]="-"
   states[2]="NSW"
   states[3]="VIC"
   states[4]="ACT"
   states[5]="QLD"
   states[6]="SA"
   states[7]="WA"
   states[8]="TAS"
   states[9]="NT"

   showStateErrorMsg(val,states,'AUSTRALIA');
}


function validateStateUS(val)
{
   var states=new Array(61)
   states[0]=""
   states[1]="-"
   states[2]="AL"
   states[3]="AK"
   states[4]="AS"
   states[5]="AZ"
   states[6]="AR"
   states[7]="CA"
   states[8]="CO"
   states[9]="CT"
   states[10]="DE"
   states[11]="DC"
   states[12]="FM"
   states[13]="FL"
   states[14]="GA"
   states[15]="GU"
   states[16]="HI"
   states[17]="ID"
   states[18]="IL"
   states[19]="IN"
   states[20]="IA"
   states[21]="KS"
   states[22]="KY"
   states[23]="LA"
   states[24]="ME"
   states[25]="MH"
   states[26]="MD"
   states[27]="MA"
   states[28]="MI"
   states[29]="MN"
   states[30]="MS"
   states[31]="MO"
   states[32]="MT"
   states[33]="NE"
   states[34]="NV"
   states[35]="NH"
   states[36]="NJ"
   states[37]="NM"
   states[38]="NY"
   states[39]="NC"
   states[40]="ND"
   states[41]="MP"
   states[42]="OH"
   states[43]="OK"
   states[44]="OR"
   states[45]="PW"
   states[46]="PA"
   states[47]="PR"
   states[48]="RI"
   states[49]="SC"
   states[50]="SD"
   states[51]="TN"
   states[52]="TX"
   states[53]="UT"
   states[54]="VT"
   states[55]="VI"
   states[56]="VA"
   states[57]="WA"
   states[58]="WV"
   states[59]="WI"
   states[60]="WY"
   states[61]="APO"
   states[62]="FPO"

   showStateErrorMsg(val,states,'the UNITED STATES');
}


