
var base = "";
if (window.location.href.indexOf('localhost') > -1 || window.location.href.indexOf('127.0.0.1') > -1) base = "/website";

function parseQueryString(key, locationString) {
    var urlArr;
    if (!locationString) {
        urlArr = location.href.split('?');
    }
    else {
        urlArr = locationString.split('?');
    }
    if (urlArr.length == 2) {
        var qsArr = urlArr[1].split('&');
        for (var i = 0; i < qsArr.length; i++) {
            var pair = qsArr[i].split('=');
            if (pair.length == 2 && pair[0] == key) {
                return pair[1];
            }
        }
    }
    return '';
}
function getQueryString() {
    var urlArr = location.href.split('?');
    if (urlArr.length == 2) {
        return urlArr[1];
    }
    else {
        return '';
    }
}

function go2(url, cmd, qstr) {
    if (url != '0') {
        if (parent && cmd == 'loginas') {
            href_string = '.php?page=' + url + '&cmd=loginas' + document.data.queryString.value;
        }
        else {
            href_string = '.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;
        }
        page = "index";
        if (qstr) {
            href_string += qstr;

            if (qstr.indexOf("template=small") != -1) {
                page = 'index_small';
            }
        }
        if (window.location.href.indexOf('index_small.php') > -1) {
            page = 'index_small';
        }

        href_string = page + href_string;
        location.href = href_string;
    }
}

function popUp(url, cmd, qstr, w, h) {
    var popUpWin;
    var w;
    var h;

    if (w == null) {
        w = 700;
    }
    if (h == null) {
        h = 600;
    }

    href_string = 'index.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;

    if (qstr) {
        href_string += qstr;
    }

    if (cmd == 'loginas') {
        href_string = base + '/app.php#app==0|url==' + href_string;
    }
    popUpWin = window.open(href_string);
    popUpWin.focus();
}

function __doPostBack(url, cmd, qstr, isNewWin) {

    if (window.location.href.indexOf('index_small.php') > -1 || parseQueryString('template', 'x?x=1' + qstr) == 'small') {
        href_string = 'index_small.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;
    }
    else {
        href_string = 'index.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;
    }

    if (qstr)
        href_string += qstr;

    document.forms[1].target = '_self';
    if (isNewWin == true) {
        var currTime = new Date().getTime();
        newWin = window.open(href_string, 'newWin' + currTime);
        document.forms[1].target = 'newWin' + currTime;
    }

    document.forms[1].action = href_string;
    document.forms[1].submit();

    if (isNewWin == true) {
        return newWin;
    }
}
function noValidation(url, cmd, qstr)
{
  if (cmd=="delete")
  {
    if(!confirm("Are you sure you want to delete?"))
      return;
  }

  __doPostBack(url, cmd, qstr);
}

//***************************
// validateForm()
//***************************
function validateForm(controls)
{
    var msg="";
    var lb="\n";
    var number_failed=0;
    // Validation *********************************************************

    //Form Validation script
    for (i=0; i<controls.length; i++)
    {  
        if (i==0)
        {
          iminusone=controls.length-1;
        }
        else
        {
          iminusone=i-1;
        }

        // if the form element is required
        if(controls[i].name.substr(0,2)=="r_" && controls[iminusone].name!=controls[i].name)
        {
          passed=true;
          
          // if the form element is a textbox or textarea
          if(controls[i].type=="text" || controls[i].type=="textarea" || controls[i].type=="hidden" || controls[i].type=="password" || controls[i].type=="file")
          {
            //alert(controls[i].name + controls[i].value.length)
            if(controls[i].value.length==0)
            {
              if(controls[i].id)
                msg+="-- "+controls[i].id+lb;
              else
                msg+=" ";
                
              passed=false;
              number_failed+=1;
            }
            
            // if the form element is meant for a email address
            else if(controls[i].name.indexOf('r_email')!=-1)
            {
              if(!isEmail(controls[i].value))
              {
                if(controls[i].id)
                  msg+="-- "+controls[i].id+lb;
                else
                  msg+=" ";
                  
                passed=false;
                number_failed+=1;
              }
            }
            else if(controls[i].name.substr(2,2)=="d_")
            {
              dateRegExp = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
        //alert(controls[i].value.match(dateRegExp));
              if(!controls[i].value.match(dateRegExp))
              {
                msg+="-- "+controls[i].id+" - (start date must be in the format MM/DD/YYYY)"+lb;
                passed=false;
                number_failed+=1;
              } 
            
            }
          }
          // if the form element is a select box
          else if(controls[i].type.substr(0,6)=="select")
          {
            if(controls[i].selectedIndex==-1 || (controls[i].selectedIndex==0 && controls[i].value=="") || controls[i].value=="")
            {
              if(controls[i].id)
                msg+="-- "+controls[i].id+lb;
              else
                msg+=" ";
                  
              passed=false;
              number_failed+=1;
            }
          }
          // if the form element is a radio button
          else if(controls[i].type=="radio")
          {
            onechecked=false;
          
            for(k=0; k<controls[controls[i].name].length; k++)
            {
              if(controls[controls[i].name][k].checked==true)
              {
                onechecked=true;
              }
            }
            
            if(onechecked==false)
            {
              if(controls[i].id)
                msg+="-- "+controls[i].id+lb;
              else
                msg+=" ";
                  
              passed=false;
              number_failed+=1;
            }
          }
          else if (controls[i].type=="checkbox")
          {
            if (controls[i].checked==false)
            {
              if(controls[i].id)
                msg+="-- "+controls[i].id+lb;
              else
                msg+=" ";

              passed=false;
              number_failed+=1;
            }
          }

          if(passed!=false)
          {
            for (j=0; j<controls.length; j++)
            {
              if(controls[i].name.substr(2)==controls[j].name)
              {
                if(controls[i].type.substr(0,6)=="select")
                {
                  var select_box=controls[i].options;
                  controls[j].value=select_box[select_box.selectedIndex].value
                  //controls[j].value=controls[i].value;
                }
                else
                {
                  controls[j].value=controls[i].value;
                }
              }
            }
          }
          
                
          if (number_failed==1)
            if (controls[i]) 
              first_failed_element=controls[i].name;
        }

    }    
    
    
    if (msg.length>0)
    {
        alert("Please enter the following information:"+lb+lb+msg);
        return false;      
    }
    else
    {
        return true;
    }
}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function validation(url, cmd, qstr) {
    var msg = "";
    var lb = "\n";
    var number_failed = 0;


    // Validation *********************************************************

    //Form Validation script
    for (i = 0; i < document.bob.elements.length; i++) {
        if (i == 0) {
            iminusone = document.bob.elements.length - 1;
        }
        else {
            iminusone = i - 1;
        }

        // if the form element is required
        if (document.bob.elements[i].name.substr(0, 2) == "r_" && document.bob.elements[iminusone].name != document.bob.elements[i].name) {
            passed = true;

            // if the form element is a textbox or textarea
            if (document.bob.elements[i].type == "text" || document.bob.elements[i].type == "textarea" || document.bob.elements[i].type == "hidden" || document.bob.elements[i].type == "password" || document.bob.elements[i].type == "file") {
                //alert(document.bob.elements[i].name + document.bob.elements[i].value.length)
                if (document.bob.elements[i].value.length == 0) {
                    if (document.bob.elements[i].id)
                        msg += "-- " + document.bob.elements[i].id + lb;
                    else
                        msg += " ";

                    passed = false;
                    number_failed += 1;
                }

                // if the form element is meant for a email address
                else if (document.bob.elements[i].name.indexOf('r_email') != -1) {
                    if (!isEmail(document.bob.elements[i].value)) {
                        if (document.bob.elements[i].id)
                            msg += "-- " + document.bob.elements[i].id + lb;
                        else
                            msg += " ";

                        passed = false;
                        number_failed += 1;
                    }
                }
                else if (document.bob.elements[i].name.substr(2, 2) == "d_") {
                    dateRegExp = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
                    //alert(document.bob.elements[i].value.match(dateRegExp));
                    if (!document.bob.elements[i].value.match(dateRegExp)) {
                        msg += "-- " + document.bob.elements[i].id + " - (start date must be in the format MM/DD/YYYY)" + lb;
                        passed = false;
                        number_failed += 1;
                    }

                }
            }
            // if the form element is a select box
            else if (document.bob.elements[i].type.substr(0, 6) == "select") {
                if (document.bob.elements[i].selectedIndex == -1 || (document.bob.elements[i].selectedIndex == 0 && document.bob.elements[i].value == "") || document.bob.elements[i].value == "") {
                    if (document.bob.elements[i].id)
                        msg += "-- " + document.bob.elements[i].id + lb;
                    else
                        msg += " ";

                    passed = false;
                    number_failed += 1;
                }
            }
            // if the form element is a radio button
            else if (document.bob.elements[i].type == "radio") {
                onechecked = false;

                for (k = 0; k < document.bob.elements[document.bob.elements[i].name].length; k++) {
                    if (document.bob.elements[document.bob.elements[i].name][k].checked == true) {
                        onechecked = true;
                    }
                }

                if (onechecked == false) {
                    if (document.bob.elements[i].id)
                        msg += "-- " + document.bob.elements[i].id + lb;
                    else
                        msg += " ";

                    passed = false;
                    number_failed += 1;
                }
            }
            else if (document.bob.elements[i].type == "checkbox") {
                if (document.bob.elements[i].checked == false) {
                    if (document.bob.elements[i].id)
                        msg += "-- " + document.bob.elements[i].id + lb;
                    else
                        msg += " ";

                    passed = false;
                    number_failed += 1;
                }
            }

            if (passed != false) {
                for (j = 0; j < document.bob.elements.length; j++) {
                    if (document.bob.elements[i].name.substr(2) == document.bob.elements[j].name) {
                        if (document.bob.elements[i].type.substr(0, 6) == "select") {
                            var select_box = document.bob.elements[i].options;
                            document.bob.elements[j].value = select_box[select_box.selectedIndex].value
                            //document.bob.elements[j].value=document.bob.elements[i].value;
                        }
                        else {
                            document.bob.elements[j].value = document.bob.elements[i].value;
                        }
                    }
                }
            }


            if (number_failed == 1)
                if (document.bob.elements[i])
                first_failed_element = document.bob.elements[i].name;
        }

    }


    msg = customFunctions(msg, url);
    if (msg.length > 0) {
        alert("Please enter the following information:" + lb + lb + msg);
    }
    else {
        if (customConfirm(url) == false) {
            return;
        }

        var page = "index";
        if (window.location.href.indexOf('index_small.php') > -1) {
            page = 'index_small';
        }

        href_string = page+'.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;
        if (qstr) {
            href_string += qstr;
        }

        document.bob.action = href_string;
        document.bob.submit();
        //return true;
    }
}


//******************************************************
//  function: customFunctions()
//  parameters: msg
//  created by:
//
//******************************************************
function customFunctions(msg, url) {
    var lb = "\n";

    if (url == "signup/ccn_info.php") {
        var lb = "\n";
        if (document.bob.r_email.value != document.bob.r_email2.value)
            msg += "-- Your email addresses do not match\n";

        if (document.bob.r_pword) {
            if (document.bob.r_pword.value != document.bob.r_pword2.value)
                msg += "-- Your passwords do not match\n";
            if (document.bob.r_pword.value.length < 6 || document.bob.r_pword2.value.length < 6)
                msg += "-- Your password must be at least 6 characters\n";
        }
        else if (document.bob.pword) {
            if (document.bob.pword.value.length > 0 || document.bob.pword2.value.length > 0) {
                if (document.bob.pword.value != document.bob.pword2.value)
                    msg += "-- Your passwords do not match\n";
                if (document.bob.pword.value.length < 6 || document.bob.pword2.value.length < 6)
                    msg += "-- Your password must be at least 6 characters\n";
            }
        }
    }
    else if (url == "client/account_info/edit_info.php") {
        if (document.bob.pword) {
            if (document.bob.pword.value.length > 0) {
                if (document.bob.pword.value != document.bob.pword2.value)
                    msg += "-- Your passwords do not match\n";
                if (document.bob.pword.value.length < 6 || document.bob.pword2.value.length < 6)
                    msg += "-- Your password must be at least 6 characters\n";
            }
        }
    }
    else if (url == "client/address_book/import2.php") {
        if (document.bob.r_address_import_type_id[2].checked == true) {
            if (document.bob.mailing_list.value.length == 0)
                msg += "-- Mailing List Name\n";
        }
        else if (document.bob.r_address_import_type_id[1].checked == true) {
            if (document.bob.selExistingGroup.selectedIndex == 0 || document.bob.selExistingGroup.selectedIndex == -1)
                msg += "-- Select an existing group\n";
        }
        if (document.bob.r_address_file.value.length > 0) {
            if (right(document.bob.r_address_file.value.toLowerCase(), 4) != ".csv")
                msg += "-- The uploaded file must be a .csv formatted file\n";
            else {
                //document.bob.btnImport.value="Importing...Please Wait...";
                document.bob.btnImport.disabled = true;
            }
        }
    }
    else if (url == "client/address_book/import3.php") {
        if (msg.length > 0) {
            document.bob.btnImport.value = "Import Contacts";
            document.bob.btnImport.disabled = false;
        }
    }
    else if (url == "client/send_cards/create_send4.php" || url == "client/corporate/previewCard.php") {
        if (document.bob.radAddressType) {
            if (document.bob.radAddressType[1]) {
                if (document.bob.radAddressType[1].checked == true) {
                    if (document.bob.fname.value.length == 0 && document.bob.lname.value.length == 0) {
                        msg += "-- First Name or Last Name" + lb;
                    }
                    if (document.bob.address1.value.length == 0 && document.bob.address2.value.length == 0) {
                        msg += "-- Address 1 or Address 2" + lb;
                    }
                    if (document.bob.zipcode.value.length == 0) {
                        if (document.bob.city.value.length == 0 && document.bob.state.value.length == 0) {
                            msg += "-- City/State or Zipcode" + lb;
                        } else {
                            if (document.bob.city.value.length == 0) {
                                msg += "-- City or Zipcode" + lb;
                            }
                            if (document.bob.state.value.length == 0) {
                                msg += "-- State or Zipcode" + lb;
                            }
                        }
                    }
                }
            }

            if (document.bob.radAddressType[0]) {
                if (document.bob.radAddressType[0].checked == true) {
                    if (document.bob.address_list_id.selectedIndex == -1 || document.bob.address_list_id.selectedIndex == 0 || document.bob.address_list_id.value.length == 0)
                        msg += "-- Address List" + lb;
                }
            }
        }

        if (document.bob.chkSaveMessage) {
            if (document.bob.chkSaveMessage.checked == true) {
                if (document.bob.message_label.value.length == 0)
                    msg += "-- Message Label" + lb;
            }
        }
    }
    else if (url == "client/campaign/save_run.php" || url == "client/corporate/saveRun.php") {
        if (document.bob.radAddressType[1].checked == true) {
            if (document.bob.fname.value.length == 0)
                msg += "-- First Name" + lb;
            if (document.bob.lname.value.length == 0)
                msg += "-- Last Name" + lb;
            if (document.bob.address1.value.length == 0)
                msg += "-- Address1" + lb;
            if (document.bob.city.value.length == 0)
                msg += "-- City" + lb;
            if (document.bob.state.value.length == 0)
                msg += "-- State" + lb;
            if (document.bob.zipcode.value.length == 0)
                msg += "-- Zip Code" + lb;
        }
        else if (document.bob.radAddressType[0].checked == true) {
            if (document.bob.address_list_id.selectedIndex == -1 || document.bob.address_list_id.selectedIndex == 0 || document.bob.address_list_id.value.length == 0)
                msg += "-- Address List" + lb;
        }

        startDate = document.bob.r_d_start_date.value;
        objStartDate = new Date();
        startDateMonth = parseInt(listgetat(startDate, 1, "/")) - 1;
        startDateDay = parseInt(listgetat(startDate, 2, "/"));
        startDateYear = parseInt(listgetat(startDate, 3, "/"));
        objStartDate.setFullYear(startDateYear, startDateMonth, startDateDay);
        objToday = new Date();
        //alert(startDateMonth + "/" + startDateDay  + "/" + startDateYear);
        /* if(objStartDate <= objToday)
        msg+="-- "+document.bob.r_d_start_date.id+" (start date must be at least one day in the future)"+lb;*/

    }

    return msg;
}

//******************************************************
//  function: customConfirm
//  parameters:
//  created by:
//
//******************************************************
function customConfirm(url) {
    if (url == "client/campaign/save_run.php") {
        // if(!confirm("Are you sure you want to create this campaign run?"))
        //      return false;
    }

    return true;

}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function checkSignUp(msg) {
    return msg;
}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function admin(cmd, id_var, id, validate) {
    if (id)
        eval("document.bob." + id_var + "_id.value=id");


    if (cmd == "add")
        eval("document.bob." + id_var + "_id.value=0");

    if (cmd == "delete") {
        if (!confirm("Are you sure you want to delete?"))
            return;
    }

    validation('admin/manage_data/' + id_var + '.php', cmd);

}


//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function manage(cmd, id_var, id, qstr) {
    if (id)
        eval("document.bob." + id_var + "_id.value=id");


    if (cmd == "add")
        eval("document.bob." + id_var + "_id.value=0");

    if (cmd == "delete") {
        if (!confirm("Are you sure you want to delete?"))
            return;
    }

    if (cmd == "list" || cmd == "view")
        noValidation('manage/accounts/' + id_var + '.php', cmd, qstr);
    else
        validation('manage/accounts/' + id_var + '.php', cmd, qstr);

}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function manage2(cmd, id_var, id, qstr) {
    if (id)
        eval("document.bob." + id_var + "_id.value=id");


    if (cmd == "add")
        eval("document.bob." + id_var + "_id.value=0");

    if (cmd == "delete") {
        if (!confirm("Are you sure you want to delete?"))
            return;
    }

    if (cmd == "list" || cmd == "view")
        noValidation('manage/products/' + id_var + '.php', cmd, qstr);
    else
        validation('manage/products/' + id_var + '.php', cmd, qstr);

}


//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function address(cmd, id_var, id, qstr) {
    if (id)
        eval("document.bob." + id_var + "_id.value=id");


    if (cmd == "add")
        eval("document.bob." + id_var + "_id.value=0");

    if (cmd == "delete" || cmd == "delete_all") {
        if (!confirm("Are you sure you want to delete?"))
            return;
    }

    if (cmd == "list" || cmd == "view")
        noValidation('client/address_book/' + id_var + '.php', cmd, qstr);
    else
        validation('client/address_book/' + id_var + '.php', cmd, qstr);

}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function sendCards(cmd, id_var, id, qstr) {
    if (id)
        eval("document.bob." + id_var + "_id.value=id");


    if (cmd == "add")
        eval("document.bob." + id_var + "_id.value=0");

    if (cmd == "delete") {
        if (!confirm("Are you sure you want to delete?"))
            return;
    }

    if (cmd == "list" || cmd == "view")
        noValidation('client/send_cards/' + id_var + '.php', cmd, qstr);
    else
        validation('client/send_cards/' + id_var + '.php', cmd, qstr);

}

//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function checkUncheck(checkbox, name) {
    if (!name) {
        if (checkbox.checked == true) {
            for (i = 0; i < document.bob.elements.length; i++) {
                if (document.bob.elements[i].type == "checkbox")
                    document.bob.elements[i].checked = true;
            }
        }
        else {
            for (i = 0; i < document.bob.elements.length; i++) {
                if (document.bob.elements[i].type == "checkbox")
                    document.bob.elements[i].checked = false;
            }
        }
    }
    else {
        if (checkbox.checked == true) {
            for (i = 0; i < document.bob.elements.length; i++) {
                if (document.bob.elements[i].type == "checkbox" && document.bob.elements[i].name.indexOf(name) != -1)
                    document.bob.elements[i].checked = true;
            }
        }
        else {
            for (i = 0; i < document.bob.elements.length; i++) {
                if (document.bob.elements[i].type == "checkbox" && document.bob.elements[i].name.indexOf(name) != -1)
                    document.bob.elements[i].checked = false;
            }
        }
    }
}



//****************************************************************************
//
//  function: isEmail
//  parameters: mailfield
//  created by: 
//  purpose: validates email address
//           
//****************************************************************************

function isEmail(mailfield) {
    // Return false if e-mail field is blank.   
    if (mailfield == "") {
        return false;
    }

    // Return false if e-mail field does not contain a '@' and '.' .   
    if (mailfield.indexOf('@', 0) == -1 || mailfield.indexOf('.', 0) == -1) {
        return false;
    }
    else {
        return true;
    }
}



//******************************************************
//  function:
//  parameters:
//  created by:
//
//******************************************************
function sameAsShipping(cmd) {
    if (cmd == true) {
        document.bob.r_billing_name.value = document.bob.r_fname.value + ' ' + document.bob.r_lname.value;
        document.bob.r_billing_address1.value = document.bob.r_address1.value;
        document.bob.billing_address2.value = document.bob.address2.value;
        document.bob.r_billing_city.value = document.bob.r_city.value;
        document.bob.r_billing_state.value = document.bob.r_state.value;
        document.bob.r_billing_zipcode.value = document.bob.r_zipcode.value;
    }
    else {
        document.bob.r_billing_name.value = "";
        document.bob.r_billing_address1.value = "";
        document.bob.billing_address2.value = "";
        document.bob.r_billing_city.value = "";
        document.bob.r_billing_state.value = "";
        document.bob.r_billing_zipcode.value = "";
    }
}


function exportAB(url) {
    href_string = url + "?z=" + document.data.queryString.value;
    document.bob.action = href_string;
    document.bob.submit();
}

function submitAction(url) {
    href_string = url + "?z=" + document.data.queryString.value;
    document.bob.action = href_string;
    document.bob.submit();
}


function openWin(url, cmd, qstr, w, h) {
    var newWin;
    var w;
    var h;
    var scrollbars;

    if (w == null) {
        w = 650;
    }
    if (h == null) {
        h = 600;
    }
    scrollbars = "yes";

    if (url == "zipcode.php") {
        w = 100;
        h = 100;
        loadZipcode(url, cmd, qstr);
        return;
    }
    else if (url == "help/signing_up.php") {
        h = 350;
    }
    else if (url == "overview/screenDemo2k7.php") {
        w = 850;
        h = 650;
        scrollbars = "no";
    }

    href_string = 'index_small.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;

    if (qstr)
        href_string += qstr;

    newWin = window.open(href_string, 'newWin', 'toolbar=no,menubar=no,scrollbars=' + scrollbars + ',locationbar=no,statusbar=no,width=' + w + ',height=' + h);
}

function openWin2(url) {
    var newWin2 = window.open(url, 'Edit_Address', 'toolbar=no,menubar=no,scrollbars=no,locationbar=no,statusbar=no,width=320,height=350');
}

function checkCharLen(textarea) {
    str = textarea.value

    //document.bob.counter.value="here";
    curIndex = 0;
    carriage_rtn = 0;

    trythis = true;
    curStart = 0;
    curLines = 0;
    lineLen = 36;
    maxLines = 9;
    countLoops = 0;
    output = "";
    nextSpaceIndex = -1;
    while (trythis == true) {
        //curSpaceIndex=-1;
        //spaceLineLoc=-1;
        //nextWordLen=0;
        //nextSpaceIndex=-1;
        //spaceDiff=0;
        curSubStr = "";
        curStartPlusLineLen = 0;

        curStartPlusLineLen = curStart + lineLen;
        if (curStart >= str.length)
            break;

        output += "--------------------------\n";
        output += "curStart: " + curStart + "\n";
        output += "curStartPlusLineLen: " + curStartPlusLineLen + "\n";
        output += "charCodeAt: " + str.charCodeAt(curStartPlusLineLen) + "\n";
        output += "str.length: " + str.length + "\n";
        curSubStr = str.substring(curStart, curStart + (lineLen));

        output += "curSubStr: " + curSubStr + "\n";

        if (curSubStr.indexOf('\n') > -1) {
            curLines++;
            curStart = curSubStr.indexOf('\n') + curStart + 1;
            output += "stop1\n";
        }
        else if (str.charCodeAt(curStartPlusLineLen) == 32) {
            curLines++;
            curStart += lineLen + 1;
            output += "stop2\n";
        }
        else if (str.charCodeAt(curStartPlusLineLen) == 45) {
            curLines++;
            curStart += lineLen + 1;
            output += "stop2\n";
        }
        else if (str.charAt(curStartPlusLineLen) == "\n") {
            curLines++;
            curStart += lineLen + 1;
            output += "stop3\n";
        }
        else if (curStartPlusLineLen >= str.length) {
            //cause to exit loop
            curStart = str.length + 20;
            curLines++;
            output += "stop4\n";
        } /*
    else if(curSubStr.lastIndexOf('-')>-1) // && navigator.appName.indexOf('Explorer')>-1
    {
      curSpaceIndex = curSubStr.lastIndexOf('-')+curStart;
      output += "curSpaceIndex: "+ curSpaceIndex + "\n";
      spaceLineLoc = (curSpaceIndex+1);
      output += "spaceLineLoc: "+ spaceLineLoc + "\n";
      nextWordLen = (curStart+lineLen+1)-spaceLineLoc;
      output += "nextWordLen: "+nextWordLen + "\n";
      if (str.indexOf('-', curStart+lineLen)==-1)
        nextSpaceIndex = str.length-1;
      else
        nextSpaceIndex = str.indexOf('-', curStart+lineLen);
        
      output += "nextSpaceIndex: "+nextSpaceIndex + "\n";
      spaceDiff=(nextSpaceIndex+1)-spaceLineLoc;
      lastSpaceDiff=spaceDiff;
      output += "spaceDiff: "+spaceDiff + "\n";
      if (spaceDiff>=nextWordLen)
      {
        if (navigator.appName.indexOf('Netscape')>-1)
        {
          startStr=str.substring(0, spaceLineLoc);
          endStr=str.substring(spaceLineLoc);
          output += "startStr: "+startStr + "\n";
          output += "endStr: "+endStr + "\n";
          textarea.value = startStr + '\n' + endStr;
          nextSpaceIndex++; 
        }
        curLines++;
        curStart=(nextSpaceIndex+1)-spaceDiff;
      }
    }*/
        else if (curSubStr.lastIndexOf(' ') > -1) {
            curSpaceIndex = curSubStr.lastIndexOf(' ') + curStart;
            output += "curSpaceIndex: " + curSpaceIndex + "\n";
            spaceLineLoc = (curSpaceIndex + 1);
            output += "spaceLineLoc: " + spaceLineLoc + "\n";
            nextWordLen = (curStart + lineLen + 1) - spaceLineLoc;
            output += "nextWordLen: " + nextWordLen + "\n";
            if (str.indexOf(' ', curStart + lineLen) == -1)
                nextSpaceIndex = str.length - 1;
            else
                nextSpaceIndex = str.indexOf(' ', curStart + lineLen);

            output += "nextSpaceIndex: " + nextSpaceIndex + "\n";
            spaceDiff = (nextSpaceIndex + 1) - spaceLineLoc;
            lastSpaceDiff = spaceDiff;
            output += "spaceDiff: " + spaceDiff + "\n";
            if (spaceDiff >= nextWordLen) {
                //output+="here2\n";
                curLines++;
                curStart = (nextSpaceIndex + 1) - spaceDiff;
            }

        }
        else
            break;

        countLoops++;

        if (curStart == str.length + 1 || countLoops > 100)
            trythis = false;
    }

    if (str.charAt(str.length - 1) == '\n') {
        curLines++;
    }


    output += "curLines: " + curLines + "\n";
    //strlen = carriage_rtn + 240;
    output += "textarea.value.length: " + textarea.value.length + "\n";
    //output += "strlen: "+strlen + "\n";

    //if (textarea.value.length>strlen)
    //  textarea.value=textarea.value.substring(0,strlen);
    //else 

    if (curLines > maxLines) {
        //alert(textarea.value.charCodeAt(textarea.value.length-1));
        subtraction = 1;
        if (navigator.appName.indexOf('Explorer') > -1 && textarea.value.charAt(textarea.value.length - 1) == '\n')
            subtraction = 2;
        else if (navigator.appName.indexOf('Explorer') > -1 && textarea.value.charCodeAt(textarea.value.length - 1) == 32)
            subtraction = 2;

        newValue = textarea.value.length - subtraction;
        output += "newValue: " + newValue + "\n";
        textarea.value = textarea.value.substring(0, newValue);
        output += "textarea.value.indexOf('\n'): " + textarea.value.indexOf('\n') + "\n";
        checkCharLen(textarea);
    }

    //document.bob.counter.value=output;
}
function listappend(list, list_item, delimiter) {
    if (list.length == 0)
        return list_item;
    else if (list.length > 0)
        return list + delimiter + list_item;
}

function listcontains(list, str, delimiter) {
    lswitch = 1;
    list_item = "";
    index1 = 0;
    index2 = 0;
    lList = list;
    lListContains = 0;
    counter = 0;
    loopcounter = 0;

    if (list.length > 0) {
        do {
            loopcounter++;
            index2 = lList.indexOf(delimiter);

            if (index2 == -1) {
                list_item = lList;
                lswitch = 0;
            }
            else if (index2 > index1) {
                list_item = lList.substring(0, index2 - index1);

                if (list_item.length > 0)
                    counter = counter + 1;

                curLength = lList.length - (index2 + 1);
                if (curLength > 0)
                    lList = right(lList, curLength);

                if (list_item.indexOf(str) != -1) {
                    lListContains = counter;
                    lswitch = 0;
                }
            }
        }
        while (lswitch == 1)
    }
    else
        lListContains = 0;


    return lListContains;
}

function listfind(list, str, delimiter) {
    lswitch = 1;
    list_item = "";
    index1 = 0;
    index2 = 0;
    lList = list;
    lListFind = 0;
    counter = 0;
    loopcounter = 0;

    if (list.length > 0) {
        do {
            loopcounter++;
            index2 = lList.indexOf(delimiter);

            if (index2 == -1) {
                list_item = lList;
                lswitch = 0;
            }
            else if (index2 > index1)
                list_item = lList.substring(0, index2 - index1);

            if (list_item.length > 0) {
                counter = counter + 1;

                curLength = lList.length - (index2 + 1);
                if (curLength > 0)
                    lList = right(lList, curLength);

                if (list_item == str) {
                    lListFind = counter;
                    lswitch = 0;
                }
            }


        } while (lswitch == 1)
    }
    else
        lListFind = 0;


    return lListFind;

}

function listlen(list, delimiter) {
    lswitch = 1;
    list_item = "";
    index1 = 0;
    index2 = 0;
    lList = list;
    counter = 0;
    loopcounter = 0;

    if (list.length > 0) {
        do {
            loopcounter++;
            index2 = lList.indexOf(delimiter);
            if (index2 == -1) {
                list_item = lList;
                lswitch = 0;
            }
            else if (index2 > index1) {
                list_item = lList.substring(0, index2 - index1);
            }

            if (list_item.length > 0) {
                counter = counter + 1;
                curLength = lList.length - (index2 + 1);
                if (curLength > 0)
                    lList = right(lList, curLength);
            }
            else
                lswitch = 0;

        } while (lswitch == 1)
    }

    return counter;

}

function listgetat(list, index, delimiter) {
    lswitch = 1;
    list_item = "";
    index1 = 0;
    index2 = 0;
    lList = list;
    counter = 0;
    lListGetAt = "";

    if (list.length > 0) {
        do {
            index2 = lList.indexOf(delimiter);

            if (index2 == -1) {
                list_item = lList;
                lswitch = 0;
            }
            else if (index2 > index1)
                list_item = lList.substring(0, index2 - index1);


            if (list_item.length > 0) {
                counter = counter + 1;

                if (counter == index) {
                    lListGetAt = list_item;
                    lswitch = 0;
                }
                else {
                    curLength = lList.length - (index2 + 1);
                    if (curLength > 0)
                        lList = right(lList, curLength);
                }

            }
        } while (lswitch == 1)
    }

    return lListGetAt;
}

function listdeleteat(list, index, delimiter) {

    lswitch = 1;
    list_item = "";
    index1 = 0;
    index2 = 0;
    lList = list;
    counter = 0;
    lListDeleteAt = "";

    if (list.length > 0) {
        do {
            index2 = lList.indexOf(delimiter);

            if (index2 == false) {
                list_item = lList;
                lswitch = 0;
            }
            else if (index2 > index1)
                list_item = lList.substring(0, index2 - index1);

            if (list_item.length > 0) {
                counter = counter + 1;

                if (index == counter) {
                    temp_str = delimiter + list_item;
                    if (list_item == listgetat(list, listlen(list, delimiter), delimiter))
                        lListDeleteAt = left(list, list.length - temp_str.length);
                    else if (counter == 1)
                        lListDeleteAt = right(list, list.length - temp_str.length);
                    else
                        lListDeleteAt = list.substring(0, list.indexOf(temp_str)) + right(list, list.length - (list.indexOf(temp_str) + temp_str.length));

                    lswitch = 0;
                }
                else {
                    curLength = lList.length - (index2 + 1);
                    if (curLength > 0)
                        lList = right(lList, curLength);
                }

            }
        } while (lswitch == 1)
    }

    return lListDeleteAt;

}

function listfirst(list, delimiter) {
    return listgetat(list, 1, delimiter);
}

function listlast(list, delimiter) {
    return listgetat(list, listlen(list, delimiter), delimiter);
}


function right(str, howManyCharsFromRight) {
    strLen = str.length;
    return str.substring(strLen - howManyCharsFromRight, strLen);
}


function moneyFmt(amt) {
    amt = round_decimals(amt, 2);
    returnValue = amt;
    index1 = amt.indexOf(".");

    if (index1 > 0) {
        //number=left(amt, index1);
        //fraction=right(amt, strlen(amt)-index1);
        //if(strlen(number)>3)
        //{
        //  amt=left(number, strlen(number)-3).",".right(number, 3).fraction;
        //}

        difference = amt.length - index1;
        if (difference == 2)
            returnValue = amt + "0";
        else
            returnValue = amt;
    }
    else {
        //number=amt;
        //if(strlen(number)>3)
        //{
        //  amt=left(amt, strlen(amt)-3).",".right(amt, 3);
        //}
        returnValue = amt + ".00";
    }
    return returnValue;

}


function DiffDays(S1, S2) {

    var X = ReadISO8601date(S1);
    if (X < 0) {
        return "Date 1 bad";
    }
    var Y = ReadISO8601date(S2);
    if (Y < 0) {
        return "Date 2 bad";
    }
    var Dx = Date.UTC(X[0], X[1] - 1, X[2]);
    var Dy = Date.UTC(Y[0], Y[1] - 1, Y[2]);
    return (Dx - Dy) / 86400000;

}

function ValidDate(y, m, d) {
    with (new Date(y, m, d)) {
        return (getMonth() == m && getDate() == d);
    }
}

function ReadISO8601date(Q) {
    var T;
    if ((T = /^(\d+)([-\/])(\d\d)(\2)(\d\d)$/.exec(Q)) == null) {
        return -2;
    }
    for (var j = 1; j <= 5; j += 2) {
        T[j] = +T[j];
    }
    if (!ValidDate(T[1], T[3] - 1, T[5])) {
        return -1;
    }
    return [T[1], T[3], T[5]];
}



/* This script is Copyright (c) Paul McFedries and 
Logophilia Limited (http://www.mcfedries.com/).
Permission is granted to use this script as long as 
this Copyright notice remains in place.*/

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()

    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {

        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0

        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }

    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length

    if (pad_total > 0) {

        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++)
            value_string += "0"
    }
    return value_string
}

function openPhotoWin(photo, site_version) {
    //href_string = site_version+"/photo.php?pn="+photo
    href_string = site_version + "/images/" + photo;
    newWin = window.open(href_string, 'newWin', 'toolbar=no,menubar=no,scrollbars=no,locationbar=no,statusbar=no,status=no,width=380,height=245');
}


function openPhotoWin2(photo, site_version) {
    href_string = site_version + "/photo2.php?pn=" + photo
    newWin = window.open(href_string, 'newWin', 'toolbar=no,menubar=no,scrollbars=no,locationbar=no,statusbar=no,status=no,width=650,height=400');
}


//******************************************AJAX


var span;
var UNINITIALIZED = 0;
var LOADING = 1;
var LOADED = 2;
var INTERACTIVE = 3;
var COMPLETE = 4;


function getHTTPRequestObject() {
    var xmlHttpRequest;
    /*@cc_on
    @if (@_jscript_version >= 5)
    try {
        xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (exception1) {
        try {
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (exception2) {
            xmlhttp = false;
        }
    }
    @else
    xmlhttpRequest = false;
  @end
    @*/

    if (!xmlHttpRequest && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlHttpRequest = new XMLHttpRequest();
        } catch (exception) {
            xmlHttpRequest = false;
        }
    }
    return xmlHttpRequest;
}

var zipcodeRequest = getHTTPRequestObject(); // Create the xml http object on the page load

function loadZipcode(url, cmd, qstr) {
    var href_string = 'index_small.php?page=' + url + '&cmd=' + cmd + document.data.queryString.value;
    if (qstr) {
        href_string += qstr;
    }

    zipcodeRequest.open('get', sv + '/zipcode2.php?cmd=' + cmd + qstr);
    zipcodeRequest.onreadystatechange = displayZipcode;
    zipcodeRequest.send(null);
}

function loadLocation(zipcodeId, cityId, stateId) {
    $.ajax({
        url: base + '/service.php?action=zipcodeLookup&zipcode=' + $('#' + zipcodeId).val() + '&type=json',
        dataType: 'json',
        success: function(data) {
            if (data.results && data.results.status == 'ok') {
                $('#' + cityId).val(data.results.location.city);
                $('#' + stateId).val(data.results.location.stateCode);
            }
        },
        error: function(request, textStatus, err) { }
    });
}

function displayZipcode() {

    if (zipcodeRequest.readyState == COMPLETE) {
        if (zipcodeRequest.status == 200) {
            var cityState = zipcodeRequest.responseText;
            //alert(cityState);
            if (cityState != "NULL") {
                var city = listgetat(cityState, 1, ",");
                var state = listgetat(cityState, 2, ",");
                var cityInput = listgetat(cityState, 3, ",");
                var stateInput = listgetat(cityState, 4, ",");

                for (i = 0; i < document.bob.elements.length; i++) {
                    if (document.bob.elements[i].name == cityInput) {
                        document.bob.elements[i].value = city;
                        document.bob.elements[i].focus();
                    }
                    else if (document.bob.elements[i].name == stateInput)
                        document.bob.elements[i].value = state;
                }
            }
            else {
                //alert("The zipcode you entered is not valid.");
            }

        }
        else {
            //alert(zipcodeRequest.responseText); 
        }
    }
}


// Example: obj = findObj("image1");
function findObj(theObj, theDoc) {
    var p, i, foundObj;

    if (!theDoc) theDoc = document;
    if ((p = theObj.indexOf("?")) > 0 && parent.frames.length) {
        theDoc = parent.frames[theObj.substring(p + 1)].document;
        theObj = theObj.substring(0, p);
    }
    if (!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
    for (i = 0; !foundObj && i < theDoc.forms.length; i++)
        foundObj = theDoc.forms[i][theObj];
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
        foundObj = findObj(theObj, theDoc.layers[i].document);
    if (!foundObj && document.getElementById) foundObj = document.getElementById(theObj);

    return foundObj;
}


function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == 0) {
        myField.focus();
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    }
    else {
        myField.value += myValue;
    }
}


function urlEncode(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    histogram['!'] = '%21';
    histogram['%20'] = '+';

    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%" + m2.toUpperCase();
    });

    return ret;
}
function setSession(value) {
    document.data.queryString.value = '&q='+value;
    //alert(document.data.queryString.value);
}



var orderCallback;
function getTotalOrderCost(callback, sessionkey, accountid, items, featureid, featurequantity, addresscount, vendorCatalogItem, cardTypeFeatureId, bulkOrderQty, bulkShippingType, countByCountry, isStandardPostage, spMin) {
    orderCallback = callback;
    var params = "";
    params += "&sessionkey=" + sessionkey;
    if (items) params += "&items=" + items;
    params += "&aid=" + accountid;
    if (featureid) params += "&fid=" + featureid;
    if (featurequantity) params += "&fq=" + featurequantity;
    if (addresscount) params += "&ac=" + addresscount;
    params += "&mt=1";
    if (vendorCatalogItem) params += "&vci=" + vendorCatalogItem;
    if (cardTypeFeatureId) params += "&ctfid=" + cardTypeFeatureId;
    if (bulkOrderQty) params += "&boq=" + bulkOrderQty;
    if (bulkShippingType) params += "&bst=" + bulkShippingType;
    if (countByCountry) params += "&cbc=" + countByCountry;
    if (isStandardPostage) params += "&sp=" + isStandardPostage;

    if (!isStandardPostage || isStandardPostage == 'false' || addresscount >= spMin) {
        priceReq = new Request(base + "/service.php?action=getTotalOrderPrice" + params, "", getTotalOrderCost_onLoad, getTotalOrderCost_onComplete, getTotalOrderCost_onError);
        priceReq.loadText();
    }
    else {
        standardPostageError(spMin);
    }

}
function getTotalOrderCost_onLoad() {
}
function getTotalOrderCost_onComplete() {
    orderCallback(priceReq.text());
}
function getTotalOrderCost_onError() {
}

//email pricing
var emailOrderCallback;
function getTotalOrderCostEmail(callback, sessionkey, accountid, items, featureid, featurequantity, addresscount) {
    emailOrderCallback = callback;
    var params = "";
    params += "&sessionkey=" + sessionkey;
    if (items) params += "&items=" + items;
    params += "&aid=" + accountid;
    if (featureid) params += "&fid=" + featureid;
    if (featurequantity) params += "&fq=" + featurequantity;
    if (addresscount) params += "&ac=" + addresscount;
    params += "&mt=2";

    var base = "";
    if (window.location.href.indexOf('localhost') > -1 || window.location.href.indexOf('127.0.0.1') > -1) base = "/website";

    priceReq = new Request(base + "/service.php?action=getTotalOrderPrice" + params, "", getTotalOrderCostEmail_onLoad, getTotalOrderCostEmail_onComplete, getTotalOrderCostEmail_onError);
    priceReq.loadText();
}
function getTotalOrderCostEmail_onLoad() {
}
function getTotalOrderCostEmail_onComplete() {
    emailOrderCallback(priceReq.text());
}
function getTotalOrderCostEmail_onError() {
    alert('error');
}

//letter pricing
var letterOrderCallback;
function getTotalOrderCostLetter(callback, sessionkey, accountid, items, featureid, featurequantity, addresscount, countByCountry, isStandardPostage, spMin) {
    letterOrderCallback = callback;
    var params = "";
    params += "&sessionkey=" + sessionkey;
    if (items) params += "&items=" + items;
    params += "&aid=" + accountid;
    if (featureid) params += "&fid=" + featureid;
    if (featurequantity) params += "&fq=" + featurequantity;
    if (addresscount) params += "&ac=" + addresscount;
    params += "&mt=3";
    if (countByCountry) params += "&cbc=" + countByCountry;
    if (isStandardPostage) params += "&sp=" + isStandardPostage;

    var base = "";
    if (window.location.href.indexOf('localhost') > -1 || window.location.href.indexOf('127.0.0.1') > -1) base = "/website";

    if (!isStandardPostage || isStandardPostage == 'false' || addresscount >= spMin) {
        priceReq = new Request(base + "/service.php?action=getTotalOrderPrice" + params, "", getTotalOrderCostLetter_onLoad, getTotalOrderCostLetter_onComplete, getTotalOrderCostLetter_onError);
        priceReq.loadText();
    }
    else {
        standardPostageError(spMin);
    }
}
function getTotalOrderCostLetter_onLoad() {
}
function getTotalOrderCostLetter_onComplete() {
    letterOrderCallback(priceReq.text());
}
function getTotalOrderCostLetter_onError() {
    alert('error');
}

function standardPostageError(spMin) {
    alert('Standard Postage requires a minimum order size of ' + spMin + ' pieces');
}

var currentScrollHeight = null;
function checkScrollHeight() {
    newHeight = $(document).contents().find('body').attr('scrollHeight');
    if (currentScrollHeight != newHeight) {
        currentScrollHeight = newHeight;
        parent.setiFrameSize(0, currentScrollHeight);
    }
}

$(document).ready(function() {
    if (window != parent) {

        setInterval(checkScrollHeight, 400);

        if (!parent.hasSession() && (parseQueryString('page') == 'client/index.php')) {
            var ajaxUrl = base + '/service.php?action=hasdatamanager&q=' + parseQueryString('q');
            parent.setSession(parseQueryString('q'));
            $.ajax({
                url: ajaxUrl,
                async: false,
                success: function(data) {
                    if (data == "1") {
                        parent.loadDataManager('index.php?page=' + parseQueryString('page') + '&q=' + parseQueryString('q') + '&cmd=logindm');
                        parent.login(true);
                    }
                    else {
                        parent.login(false);
                    }
                }
            });
        }
        else if (parseQueryString('page') == 'login/accountSelector.php') {
            parent.clearSession();
        }

        $('.dmaccountselector').css('display', 'none');
        if (parent.getHasDataManager()) {
            $('td:contains("Logout")').css('display', 'none');
            $('#spanLoginSpacer').css('display', 'none');
        }
    }
});


function getAccountBalance(sid) {
    var accountBal = 0;
    $.ajax({ url: base + '/service.php?action=getAccountBalance&q=' + sid, success: function(data) { accountBal = parseFloat(data); }, async: false });
    return parseFloat(accountBal);
}
