
// Global Variables for all form scripts to use
var subcat = new Array();
var asize = 0;

var dists = new Array();
var dsize = 0;

// ** Totals selected Districts to Subtotal ** //
function globalCall(update,controller,params,display) {
   display = typeof(display) != 'undefined' ? display : 0;
   function ajax_response(resp) {
      if (display == 0) {
         document.getElementById(update).style.display = 'block';
      }
   }
   var url = controller;
   var pars = params;
   var target = update;
   var myAjax = new Ajax.Updater(target, url, {evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}

//////////////////////////////////////////////////////
// Is Num? Function //
function form_input_is_int(input){
  return !isNaN(input)&&parseInt(input)==input;
}

// Auto Tab Credit Card //
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];

    if (!form_input_is_int(input.value)) { input.value="";return false; }

    if(input.value.length >= len && !containsElement(filter,keyCode))

    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
    found = true;
else
    index++;
    return found;
}

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
    }

return true;
}


function ccOff(option) {
   var ccnums = document.getElementsByName('cardnumber[]');
   for (i = 0;i <= ccnums.length;++i) {
      ccnums[i].disabled = option;
   }
}

function toggleDiv(divId) {
   var toggleIt = document.getElementById(divId);
   if (toggleIt.style.display == "none") { toggleIt.style.display = "block"; } else { toggleIt.style.display = "none"; }
}

function showDiv(divId) {
   document.getElementById(divId).style.display = "block";
}

function hideDiv(divId) {
   document.getElementById(divId).style.display = "none";
}

function hideAdvertiser(advId) {
   globalCall('hideshow_'+advId,'/admin/advertisers','h='+advId);
}

function showAdvertiser(advId) {
   globalCall('hideshow_'+advId,'/admin/advertisers','s='+advId);
}

function showAgent(agntId) {
   globalCall('hideshow_'+agntId,'/admin/agents/index','s='+agntId);
}

function hideAgent(agntId) {
   globalCall('hideshow_'+agntId,'/admin/agents/index','h='+agntId);
}

function activateAgent(agntId) {
   globalCall('hideshow_'+agntId,'/admin/agents/index','a='+agntId);
}

function cBread(cid,cname) {
   alert(cid);
   alert(cname);
}

function pBread(pid,pname) {
   alert(pid);
   alert(pname);
}

function hideBMs() {
   document.getElementById('clist').style.display = 'none';
   document.getElementById('plist').style.display = 'none';
   document.getElementById('dlist').style.display = 'none';
}


function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(selObj.options[selObj.selectedIndex].id);
  if (restore) selObj.selectedIndex=0;
}

function showAgents(district) {
    function ajax_response(resp) {
    }
    var url = '/ajax/agents/index';
    var pars = 's=1&d='+district;
    var target = "main";
    var myAjax = new Ajax.Updater(target, url, {  evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}

function displayAgent(aid) {
    cleanArrays();
    function ajax_response(resp) {
       //document.getElementById('editbox').style.visibility = 'visible';
       showbox('editbox');
    }
    var url = '/ajax/agents/index';
    var pars = 's=2&a='+aid;
    var target = "inner_main";
    var myAjax = new Ajax.Updater(target, url, {  evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}

function displayHeader(district) {
    function ajax_response(resp) {
    }
    var url = '/ajax/header';
    var pars = 'h=1';
    var target = "header_wrapper";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}


//A Fix for form serialization to enable multiple submit buttons in one form
function runIt() {
    alert('1');
}


// Form Scripts Start **********************************


//TinyMCE Related
function showTiny(yesno) {
    var tinyMCE = document.getElementById('tinyMCE');
    if (yesno == 'yes') {
        tinyMCE.style.display = "block";
    } else if (yesno == 'no') {
        tinyMCE.style.display = "none";
    }
}

function insertTiny() {
    var ttt = document.getElementById('tinyMCE');
    var yes = document.getElementById('yes');
    ttt.innerHTML = "<textarea id=\"coupontext\" name=\"coupontext\" rows=\"15\" cols=\"80\" style=\"width: 80%\"></textarea><br>";
    tinyInit();
    yes.innerHTML = "<input type='radio' checked onclick='showTiny(this.value);' name='coupon' value='yes'>";
}

function tinyInit() {
  tinyMCE.init({
    // General options
    mode : "exact",
    elements : "coupontext",
    theme : "advanced",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons2 : "code,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,insertdate,hr,|,forecolor,backcolor",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : "css/content.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "lists/image_list.js",
    media_external_list_url : "lists/media_list.js",

    force_p_newlines : false,
    force_br_newlines : true,

    // Replace values for the template plugin
    template_replace_values : {
      username : "Some User",
      staffid : "991234"
    }
  });
}
// TinyMCE end ********************


function add2Total(ppp) {
// [0] = pid
// [1] = dname
// [2] = did
// [3] = checked true/false
   function inDistArray(did) {
      var i;
      var y;
      var flag = 0;
      for (i = 0;i < window.dists.length;++i) {
         for (y = 0;y < window.dists[i][0].length;++y) {
            if (window.dists[i][2][y] == did) {
               return true;
            }
         }
      }
      return false;
   }

   function isDistChecked(did,pid) {
      var ddd = document.getElementsByName('dist[]');
      var i;
      var y;
      var flag = 0;
      var name = ddd[0].id.split('f888f');
      var exploded = name[1].split('f999f');
      var pId = exploded[0];
      for (i = 0;i < ddd.length;++i) {
         if (ddd[i].value == did && ddd[i].checked == true) {
            return true;
         }
      }
      if (pId == pid) {
         return false;
      } else {
         return true;
      }
   }
   var i;
   var y;
   var count = 0;
   var total = 0;
   var output = "<table class='advtotal' border=1 cellpadding=0 cellspacing=0 style='width:250px'><tr><th style='width:160px'>Region</th><th align=right>Amount</th></tr>";
   for (i = 0;i < window.dists.length;++i) {
      for (y = 0;y < window.dists[i][0].length;++y) {
         if (ppp) {
             ++count;
             if (count == 1) {
                total = "0.00";
             } else {
                total = "25.00";
             }
             output = output + "<tr><td>"+window.dists[i][1][y]+"</td><td align=right>$"+total+"</td></tr>";
         } else if (isDistChecked(window.dists[i][2][y],window.dists[i][0][y])) {
             ++count;
             if (count == 1) {
                total = "0.00";
             } else {
                total = "25.00";
             }
             output = output + "<tr><td>"+window.dists[i][1][y]+"</td><td align=right>$"+total+"</td></tr>";
          }
      }
   }
   var dists = document.getElementsByName('dist[]');
   for (i = 0;i < dists.length;++i) {
      if (dists[i].checked == true) {
         if (!inDistArray(dists[i].value)) {
             ++count;
             if (count == 1) {
                total = "0.00";
             } else {
                total = "25.00";
             }
            var aname = dists[i].id;
            var bname = aname.split("f888f");
            output = output + "<tr><td>"+bname[0]+"</td><td align=right>$"+total+"</td></tr>";
         }
      }
   }
   document.getElementById('tabletotal').innerHTML = output;
   var subtotal = '249';
   if (count > 0) {
      count = count - 1;
      count = count * 25;
      subtotal = subtotal*1 + count*1;
   }
   gst = subtotal * .05;
   total = subtotal*1 + gst*1;   
   total = Math.round(100*total)/100;
   total = "$" + total.toFixed(2);
   subtotal = "$" + subtotal + ".00";
   document.getElementById('subtotal').innerHTML = subtotal;
   document.getElementById('gst').innerHTML = "$" + gst.toFixed(2);
   document.getElementById('total').innerHTML = total;
   /*    var dists = document.getElementsByName('dist[]');
    var i;
    var c = 0;
    var output = "<table class='advtotal' border=1 cellpadding=0 cellspacing=0 style='width:250px'><tr><th style='width:160px'>Region</th><th align=right>Amount</th></tr>";
    var total;
    for (i = 0;i < dists.length;++i) {
      if (dists[i].checked == true) {
        ++c;
        if (c == 1) {
            total = 0;
        } else {
            total = 1;
        }
        name = dists[i].id.split('f888f');
        output = output + "<tr><td>"+name[0]+"</td><td align=right>"+total+"</td></tr>";
      }
    }
    output = output + "</table>";
    document.getElementById('tabletotal').innerHTML = output;

    var subtotal = '199';
    if (c > 0) {
        c = c - 1;
        c = c * 25;
        subtotal = subtotal*1 + c*1;
    }
    subtotal = "$" + subtotal + ".00";
    document.getElementById('subtotal').innerHTML = subtotal;
    */
}



// ** Goes through the final saved subcat array and places them in hidden input elements for submitting  ** //
function preSubmit(f) {
    document.getElementById('subcategory').innerHTML = "";
    var nodes = document.getElementsByName("cats[]");
    var i;
    var output = "";
    var catflag = 0;
    for(i = 0;i < nodes.length;++i) {
        nodes[i].disabled = false;
        if (nodes[i].checked == true) {
           catflag = 1;
        }
    }
    for(i = 0;i < window.subcat.length;++i) {
        for(x = 0;x < window.subcat[i][0].length;++x) {
            if (window.subcat[i][1][x] == true) {
                output = output + "<input type='hidden' name='subcats[]' value='"+window.subcat[i][2][x]+"'/>";
            }
        }
    }
    for (i = 0;i < window.dists.length;++i) {
        for(x =0;x< window.dists[i][0].length;++x) {
                output = output + "<input type='hidden' name='dist[]' value='"+window.dists[i][2][x]+"'/>";
        }
    }
    document.getElementById('addedsaved').innerHTML = output;

    var aForm = document.forms.testform2;
    var msg = "";
    
    if (aForm.elements[5].value.length < 2) {
       msg = "Please Enter a Valid Business Name";
    } else if (aForm.elements[10].value.length < 2) {
       msg = "Please Enter a Valid Phone";
    } else if (catflag == 0) {
      msg = "Please Check at least One Category";
    } else if (dsize < 1) {
      msg = "Please Select at least One District";
    } else if (subcat.length < 1) {
      msg = "Please Select at least One Subcategory";
    } else {
      document.forms.testform2.submit();
    }
    if (msg.length > 1) {
      document.getElementById('errormessage').innerHTML = msg;
      document.getElementById('errormessage').style.display = "block";
    }
}

function errorMessages() {
   var msg = "";
   if ($('firstname').value.length < 2) {
      $('firstname').focus();
      msg = "Please Enter a Valid First Name";
   }
   else if ($('businessname').value.length < 2) {
      $('businessname').focus();
      msg = "Please Enter a Valid Business/Brokerage Name";
   }
   else if ($('phone').value.length < 7) {
      $('phone').focus();
      msg = "Please Enter a Valid Phone Number";
   }
   else if ($('email').value.length < 3) {
      $('email').focus();
      msg = "Please Enter a Valid Email Address";
   }
   else if ($('profileurl').value.length < 3) {
      $('profileurl').focus();
      msg = "Please Enter a Valid Profile Name";
   } else if ($('isTaken').innerHTML == 0) {
      msg = "This Profile Name is Already Taken";
   } else if (dsize == 0) {
      msg = "Please Select at least One District";    
   }     
   if (msg.length > 1) {
      document.getElementById('errormessage').innerHTML = msg;
      document.getElementById('errormessage').style.display = "block";
      return false;
   } else {
      return true;
   }
}

function agentIsTaken() {
    // Is Profile Name Taken?   
    var agentForm = document.forms.agentformjoin;
    var profileName = agentForm.elements[20].value;
    globalCall('isTaken','/salespersonjoin','pn='+profileName,1);
}

function agentPreSubmit() {
    var i;
    var output = "";
    for (i = 0;i < window.dists.length;++i) {
        for(x =0;x< window.dists[i][0].length;++x) {
                output = output + "<input type='hidden' name='dist[]' value='"+window.dists[i][2][x]+"'/>";
        }
    }

    document.getElementById('addedsaved').innerHTML = output;
    agentIsTaken();
    if (errorMessages() == true) {
       return true;
    }
    return false;
}


function agentProfileName() {
    var agentForm = document.forms.agentformjoin;
    var profileName = agentForm.elements[20].value;
    var agentFirst = agentForm.elements[2].value;
    var agentLast = agentForm.elements[3].value;
    if (agentFirst.length > 1) {
       var profilename = agentFirst;
       agentForm.elements[20].value = profilename;
    }
    if (agentFirst.length > 1 && agentLast.length > 1) {
       var profilename = agentFirst + "_" + agentLast;
       agentForm.elements[20].value = profilename;
    }

   var url = '/salespersonjoin';
   var pars = 'check='+profilename;
   var target = 'isTaken';
   var myAjax = new Ajax.Updater(target, url, {evalScripts: true, method: 'get',  parameters: pars});
}

// ** Checks through the categories to find selected ones.. Once found it then checks through the saved subcats to
// ** see which ones have been saved already.. if a Category is checked and the item is not saved yet it will
// ** display the select subcategory for that checked Category :)
function checkcat() {
    var nodes = document.getElementsByName("cats[]");
    var i;
    for (i = 0;i < nodes.length;++i) {
        //alert(nodes[i].checked);
        if (nodes[i].checked == true) {
            flag = 0;
            for(x = 0;x < window.subcat.length;++x) {
                if (window.subcat[x][0][0] == nodes[i].value) {
                    flag = 1;
                }
            }
            if (flag == 0) {
                subcatForm(nodes[i].value);
            }
        }       
    }
}

// ** This function is ran after the user clicks Delete in Saved Categories it to un-disable all disabled categories
// ** which were disabled after the 3 limit max.
function cancelSub() {
    var nodes = document.getElementsByName("cats[]");
    var i;
    var x;
    for (i = 0;i < nodes.length;++i) {
      if (nodes[i].disabled != true) {
            nodes[i].disabled = false;
      }
      if (nodes[i].disabled == true && nodes[i].checked == false) {
         nodes[i].disabled = false;
      }
    }
    checkcat();
}

// ** Checks to see if 3 categories has been selected if so it disables the remaining **//
function isThree() {
   var nodes = document.getElementsByName("cats[]");
   var i;
   var c;
   c = 0;
   if (window.asize == 3) {
       for (i = 0;i < nodes.length;++i) {
           if (nodes[i].checked == true) {
               c = c + 1;
           }
       }
       if (c == 3) {
           for (i = 0;i < nodes.length;++i) {
               nodes[i].disabled = true;
           }
       }
   }
}
 
// ** After the Edit link is clicked this repopulates the checks in the boxes based on the js subcat array ** //
// subcat[a][0] = catId
// subcat[a][1] = true/false
// subcat[a][2] = subCatId
function reCheck(cid) {
    var nodes = document.getElementsByName("subcats[]");
    // Fromt his take all options from the window subcat array that are using this cid category id
    for(i = 0;i < window.subcat.length;++i) {
        if (window.subcat[i][0][0] == cid) {
            var a = i;
        }
    }
//    for(i = 0;i < nodes.length;++i) {
//        if (window.subcat[a][1][i] == true) {
//            alert(subcat[a][2][i]);
//            nodes[i].checked = true;        
//         }
//    }
//alert(nodes[0].value);
//Run through all options within this category array
   for(x = 0;x < window.subcat[a][2].length;++x) {
      //run through all the nodes subcat[] nodes
      for(i = 0;i < nodes.length;++i) {
         //if node matches id user subcat array subcat id
         if (nodes[i].value == window.subcat[a][2][x]) {
            //if user subcat array value is checked to true
            if (window.subcat[a][1][x] == true) {
               nodes[i].checked = true;
            }
         }
      }
   }

//      alert(window.subcat[a][2][x]);
}

function clearSub() {
   document.getElementById('subcategory').innerHTML = "";
}

function isUnchecked(elmnt) {
   if (elmnt.checked == false) {
      setTimeout("clearSub()",300);
   }
}

// ** After user clicks Edit on a Saved Category this will redisplay it
function editLink(cid) {
    subcatForm(cid+"&nocan=1");
    setTimeout("reCheck("+cid+")",500);
}


// ** When a user clicks Delete on a Save Category **//
function deleteLink(cid) {
  for(i = 0;i< window.subcat.length;++i) {
    if (window.subcat[i][0][0] == cid) {
        var delme = i;
    }
  }
  window.subcat.splice(delme,1);
  
  document.getElementById('catcheck_'+cid).disabled = false;
  document.getElementById('catcheck_'+cid).checked = false;
  cancelSub();
  window.asize = window.asize - 1;
  displayAdded();
}

function provUpdate(id,pname) {
    var provName = document.getElementById('provName');
    if (provName != null) {
      provName.value = pname;
    }
    var provId = document.getElementById('provId');
    if (provId != null) {
      provId.value = id;
    }
}

function toggleLocations(id) {
   var Locations = document.getElementById('Locations');
    if (id == '1') {
        locations('cf','countries','1');
        Locations.style.display = 'block';
    } else if (id == '0') {
        document.getElementById('countries').innerHTML = "";
        document.getElementById('provinces').innerHTML = "";
        document.getElementById('districts').innerHTML = "";
        Locations.style.display = 'none';
    }
}

function createDistsArray(num) {
// [0] = pid
// [1] = dname
// [2] = did
// [3] = checked true/false
// [4] = province name
    dists[num] = new Array();
    dists[num][0] = new Array();
    dists[num][1] = new Array();
    dists[num][2] = new Array();
    dists[num][3] = new Array();
    dists[num][4] = new Array();
}

function addDist() {
    var nodes = document.getElementsByName("dist[]");
    
    var isChecked = false;
    for (i = 0; i < nodes.length;++i) {
        if (nodes[i].checked == true) {
            isChecked = true;
        }
    }

    if (!isChecked) {
        alert('Please select at lease one District');
        //save();
        return false;
    }
    
    var exploded = nodes[0].id.split("f888f");
    var dName = exploded[0];    
    var exploded2 = exploded[1].split("f999f");
    var pId = exploded2[0];
    var province = exploded2[1];
    var districtDiv = document.getElementById('districts');
    var flag = 0;
    var spot = -1;
    var i;
    var delme;
    for (i = 0; i < dists.length; ++i) {
        if (dists[i][0][0] == pId) {
            delete dists[i];
            spot = i;
            flag = 1;
            break;
        }
    }

    if (spot == -1) {
        spot = dsize;
    }

    createDistsArray(spot);
    
    var c = 0;
    // 0 :: pid, 1 :: name, 2 :: distId, 3 :: checked
    for(i = 0;i < nodes.length;++i) {
        if (nodes[i].checked == true) {
            var exploded = nodes[i].id.split("f888f");
            var dName = exploded[0];
            dists[spot][0][c] = pId;        
            dists[spot][1][c] = dName;        
            dists[spot][2][c] = nodes[i].value;
            dists[spot][3][c] = nodes[i].checked;
            dists[spot][4][c] = province;
            c = c + 1;
        }
    }
    
    if (flag == 0) {
        dsize = dsize + 1;
    }
    displayDists();
    districtDiv.innerHTML = "";
    toggleLocations('0');
}


function reCheckD(pid) {
    for(i = 0;i < window.dists.length;++i) {
        if (window.dists[i][0][0] == pid) {
            var a = i;
        }
    }
    var i;
    var x;
    var nodes = document.getElementsByName("dist[]");
    for(i = 0;i < nodes.length;++i) {
       for(x = 0;x < dists[a][0].length;++x) {
          if (nodes[i].value == dists[a][2][x]) {
             nodes[i].checked = true;
          }
       }
    }
}

function editLinkD(pid) {
    toggleLocations('1');
    locations('df','districts',pid)
    setTimeout("reCheckD('"+pid+"')",500);
}

// When user deletes a saved District from Form
function deleteDistLink(pid) {
 for(i = 0;i< window.dists.length;++i) {
    if (window.dists[i][0][0] == pid) {
        var delme = i;
    }
  }
  window.dists.splice(delme,1);
  window.dsize = window.dists.length;
  add2Total(pid);
  displayDists();
}

function displayDists() {
    var displayDists = document.getElementById('displayDists');
    var output = "";
    var pname = "";
    var pid = "";
    for(i = 0;i < dists.length;++i) {
        pid = dists[i][0][0];
        pname = dists[i][4][0];
        output = output + "<div style='position:relative;font-size:14px;margin-right:20px;margin-left:20px;float:left'><div style='position:absolute;background:url(/imgs/greencheck.png);width:20px;height:18px;left:-25px'></div>"+pname+"<br><a style='font-size:11px;color:#D15E5E;font-weight:bold' href='#' onclick=\"editLinkD('"+pid+"');return false;\">Edit</a> <a style='font-size:11px;color:#D15E5E;font-weight:bold' href=\"#\" onclick=\"deleteDistLink('"+pid+"');return false;\">Delete</a></div>";
    }
    displayDists.innerHTML = output + "<a href=\"#\" style='font-size:12px;font-weight:bold;color:#D15E5E;' onclick=\"toggleLocations('1');return false;\">Add Another Province/State</a><br style='clear:both' />";
}


// ** After the uesr Saves the Selected Subcategories this write them to the array subcats ** //
function add() {
    var catnodes = document.getElementsByName("cats[]");
    var nodes = document.getElementsByName("subcats[]");
    var catid = document.getElementById("catid").value;
    var i;
    flag = 0;
    for (i = 0;i < catnodes.length;++i) {
       if(catnodes[i].value == catid) {
          catnodes[i].disabled = true;
       }
    }

    for (i = 0;i < nodes.length;++i) {
        if (nodes[i].checked == true) {
            flag = 1;
        }
    }

    if (flag == 0) {
        alert('Please select one subcategory');
        //save();
        return false;
    }
   
    flag =  0; 
    for (i = 0;i < subcat.length;++i) {
        if (subcat[i][0][0] == catid) {
            flag = 1;
            var aaa = i;
        }
    }
    if (flag == 0) {
        var aaa = asize;
        asize = asize + 1;
    }
    subcat[aaa] = new Array();
    subcat[aaa][0] = new Array();
    subcat[aaa][1] = new Array();
    subcat[aaa][2] = new Array();
    for(i = 0;i < nodes.length;++i) {
        subcat[aaa][0][i] = catid;
        subcat[aaa][1][i] = nodes[i].checked;
        subcat[aaa][2][i] = nodes[i].value;
    }
    destroyDiv('innersub');
    checkcat();
    displayAdded();
    isThree();
}


// ** After the subcats array has been written to this will display the Saved Subcats with a Green Check in a Div **//
function displayAdded() {
    var added = document.getElementById('added');
    var output = "";
    var cid;
    for(x = 0;x < subcat.length;++x) {
        cid = subcat[x][0][0];
        cname = document.getElementById('catname_'+cid).value;
        output = output + "<div style='position:relative;font:14px arial;margin-right:20px;margin-left:20px;float:left'><div style='position:absolute;background:url(/imgs/greencheck.png);width:20px;height:18px;left:-25px'></div>"+cname+"<br><a style='font:bold 12px arial;color:#D15E5E' href='#' onclick='editLink("+cid+");return false;'>Edit</a> <a style='font:bold 12px arial;color:#D15E5E' href='#' onclick='deleteLink("+cid+");return false;'>Delete</a></div>";
    }
    if (subcat.length == 1) {
        var catTitle = "Category";
    } else {
        var catTitle = "Categories";
    }
    if (window.asize > 0) {    
        added.innerHTML = "<div style='padding:9px 0px 8px 0px;font-weight:bold'>Saved "+catTitle+":</div><div style='padding:8px;width:auto'>"+output+"<br style='clear:both'></div>";
    } else {
        added.innerHTML = "";
    }
}


// Form Scripts End ************************************


function popupAd(aid) {
    function ajax_response(resp) {
       document.getElementById('popup_wrapper').style.display = 'block';

    }
    var url = '/advertisements';
    var pars = 'show='+aid;
    var target = "popupad";
    var myAjax = new Ajax.Updater(target, url, { evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}





// Related to the Advertisement coupon
function bbb() {
    function ajax_response(resp) {
    document.getElementById('coupontext').innerHTML = "ADSFDSAF";
    document.getElementById('iFrame').style.display = 'block';
    var doc = document.getElementById('iFrame');
    var aaa = doc.contentDocument;
    if (aaa == undefined || aaa == null)
            aaa = doc.contentWindow.document;

    var output = "";
    output = "<script>document.getElementById('ctext').innerHTML='adsfdsaf'</script>";
    aaa.open();
    aaa.write(output);
    aaa.close();
} 
    
    var url = '/advertisements';
    var pars = 'coupon=1';
    var target = "coupontext";
    var myAjax = new parent.Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}





function closeMe() {
    document.getElementById('iFrame').src = "";
    document.getElementById('iFrame').style.display = "none";
}




//Move this later out of ajax.js
function cupon(uid,bname,bdesc) {
    
    function ajax_response(resp) {
        var reta = document.getElementById('coupontext').innerHTML;

    var doc = document.getElementById('iFrame');
    var aaa = doc.contentDocument;
    if (aaa == undefined || aaa == null)
            aaa = doc.contentWindow.document;
    
    var scripting = "<script>function printMe() { var xxx = document.getElementById('printbutton'); xxx.style.display = 'none'; print(); } </script>";

    var doctype = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
    var style= "<style>#printbutton {position:absolute; width:102px; height:36px; bottom:19px; right:21px} </style><body>";
    var logo = "<img src='/advertisers/"+uid+"/logo.jpg'>";
    var ctop = "<img src='/imgs/coupontop.png'>";
    var cbot = "<img src='/imgs/couponbottom.png'>";
    var pbut = "<div id='printbutton'><a href='#' onclick=\"printMe();return false;\"><img style='border:0px' src='/imgs/print.png'></a></div>";
    var ctnt = "<div><div style='margin-top:-5px;float:left;margin-left:20px;padding-bottom:10px'>"+logo+"</div><div style='width:auto;text-align:center;float:right;margin-right:50px'><span style='font:bold 28px arial'>"+bname+"</span><br><span style='font:bold 14px arial'>"+bdesc+"</span></div><br style='clear:both'></div><div id='ctext' style='border-top:1px solid black;padding-top:15px'></div>"; 

    var output = doctype+"<html style='width:681px'><head>"+scripting+style+"</head><div><div style='position:absolute;right:10px;top:10px'><a href='#' onclick='parent.closeMe();return false;'><img style='border:0px' src='/imgs/redx.png'/></a></div>"+ctop+"<div style='background:url(/imgs/couponmiddle.png);backgroun-repeat:repeat-y'><div style='margin-left:40px;margin-right:40px'>"+ctnt+""+reta+"</div></div>"+cbot+"</div>"+pbut+"</body></html>";

    aaa.open();
    aaa.write(output);
    aaa.close();
    document.getElementById('iFrame').style.display = '';

    if (doc.Document && doc.Document.body.scrollHeight) {
            h = doc.Document.body.scrollHeight;
    } else if (doc.contentDocument && doc.contentDocument.body.scrollHeight) {
            h = doc.contentDocument.body.scrollHeight;
    }

    document.getElementById('iFrame').style.height = h+"px";
    document.getElementById('iFrame').style.display = 'block';
    }
    var url = '/advertisements';
    var pars = 'coupon=1&uid='+uid;
    var target = "coupontext";
    var myAjax = new parent.Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
    

}
//Move this later out of ajax.js
function iPrint(ptarget) {
    ptarget.focus();
    ptarget.print();
}

function advSearch(data) {
  function ajax_response(resp) {}
  var url = "/admin/advertisers";
  var target = 'main';
  var options = {
      evalScripts: true,
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

function agentSearch(data) {
  function ajax_response(resp) {}
  var url = "/admin/salespeople";
  var target = 'main';
  var options = {
      evalScripts: true,
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

function submitAdvertiser(data) {
  function ajax_response(resp) {}
  var url = "/advertiserjoin";
  var target = 'forminfo';
  var options = {
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

// Saves the subcats to the form in advertisers join form
function saveSubcat(data,cid) {
  function ajax_response(resp) {}
  var url = "/ajax/categories";
  var target = 'subcatlist';
  var options = {
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

function updateSortInfo(e) {
    window.setTimeout(function(evt, myVar) {return function() {
        document.getElementById('sortinfo').innerHTML="Drag and Drop to Sort List";
    } } 
    (e, "Sort"), 1000);
}


function writeOrder(data) {
  function ajax_response(resp) {
    updateSortInfo("SortSaved");
  }
  var url = "/admin/categories/sort";
  var target = 'sortinfo';
  var options = {
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

function addCategory() {
    function ajax_response(resp) {
        document.getElementById('editbox').style.visibility = 'visible';
    }
    var url = '/ajax/categories';
    var pars = 'a=add';
    var target = "subcatlist";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function updateAdvListEntry(advid) {
    function ajax_response(resp) {}
    var url = '/ajax/categories';
    var pars = 'a=u'+'&id='+advid;
    var target = "a_"+advid;
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function toggleEditBox(onoff) {
  var editbox = document.getElementById('editbox'); 
  if (onoff == '1') {
      editbox.style.display = 'block';
  }
  if (onoff == '0') {
     editbox.style.display = 'none';
  }
}

function saveCatInfo(data,cid,bname) {
  toggleEditBox('0');
  function ajax_response(resp) {
   // document.getElementById('btn_t'+cid).innerHTML = bname;
     getSubcats(cid);
  }
  var url = "/ajax/categories";
  var target = 'subcatlist';
  new Ajax.Updater(target,url, { evalScripts:true, method:"post",postBody:data,onComplete:ajax_response });
}

function postSubcat(data,cid) {
  function ajax_response(resp) {
    getSubcats(cid);
  }
  var url = "/ajax/categories";
  var target = 'subcatlist';
  var options = {
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}


function saveAdvertiser(data,advid) {
  function ajax_response(resp) {
    updateAdvListEntry(advid);
  }
  var url = "/ajax/categories";
  var target = 'inner_main';
  var options = {
      method:"post",
        postBody:data,
        onComplete:ajax_response
  };
  new Ajax.Updater(target,url,options);
}

function updateDate(adate,tdate) {
    document.getElementById('adate').value=adate;
    document.getElementById('cal').style.border = '0px solid white';
    document.getElementById('cal').style.padding = '6px 0px 0px 8px';
    document.getElementById('cal').style.font = '13px arial';
    document.getElementById('cal').innerHTML=tdate;
}

function calstart(parms) {
    function ajax_response(resp) { 
        document.getElementById('cal').style.border = "5px solid #E8E8E8"; 
        document.getElementById('cal').style.padding = "0px"; 
    }
    var url = '/ajax/cal';
    var pars = parms;
    var target = "cal";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function destroyDiv(div) {
    var DIVtoRemove = document.getElementById(div);
    DIVtoRemove.parentNode.removeChild(DIVtoRemove);
}


function dAdvertisers(sid,did) {
    function ajax_response(resp) {}
    var url = '/ajax/categories';
    var pars = 'a=show'+'&sid='+sid+'&did='+did;
    var target = "main";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function categories(type,div,id) {
   document.getElementById('main').innerHTML = "";
    if (type == 'c') { 
        document.getElementById('categories').innerHTML = "";
        document.getElementById('subcategories').innerHTML = "";
    }
    //type :: c = categories s = subcategories
    function ajax_response(resp) {}
    var url = '/ajax/categories';
    var pars = 'a='+type+'&id='+id;
    var target = div;
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function locations(type,div,id) {
    //type :: c = countries, p = provinces, d = distrcts
    function ajax_response(resp) {}
    if (type == 'c' || type == 'ch') {
        document.getElementById('provinces').innerHTML = "";
        document.getElementById('districts').innerHTML = "";
    }
    if (type == 'p' || type == 'ph') {
        document.getElementById('provinces').innerHTML = "";
        document.getElementById('districts').innerHTML = "";
    }
    document.getElementById('categories').innerHTML = "";
    document.getElementById('subcategories').innerHTML = "";

    var url = '/ajax/locations';
    var pars = 'a='+type+'&id='+id;
    var target = div;
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function removeItems(array) {
    var i = 0;
    while (i < array.length) {
            array.splice(i, 1);
    }
}


function cleanArrays() {
    // asize is reset because its the counter for the Saved Subcategories clear before loading the next AdvForm 
    asize = 0;
    dsize = 0;
    var i;
    var x;
    // below is a method to clean the array so old Districts & Saved Subcategories don't show in the next users list
    for (i = 0; i < subcat.length; ++i) {
        for(x = 0; x < subcat[i].length; ++x) {
           removeItems(subcat[i][x]); 
        }
        removeItems(subcat[i]);
    }
    removeItems(subcat);
    for (i = 0; i < dists.length; ++i) {
        for(x = 0; x < dists[i].length; ++x) {
           removeItems(dists[i][x]);
        }
        removeItems(dists[i]);
    }
    removeItems(dists);
}

function adminAdvertisers(type,advid) {
    //type :: s = show
    function ajax_response(resp) {
//        document.getElementById('editbox').style.visibility = 'visible';
          showbox('editbox');
    //displayDists();
    //isThree();
    //add2Total();

    }
    //cleanArrays();
    var url = '/ajax/advertisers';
    var pars = 'a=s&id='+advid;
    var target = 'inner_main';
    var myAjax = new Ajax.Updater(target, url, {  evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}

function getSubcats(button) {
    function ajax_response(resp) {
       showbox('editbox');
    }
    var url = '/ajax';
    var pars = 'a=subcats&b='+button;
    var target = 'subcatlist';
    var myAjax = new Ajax.Updater(target, url, { evalScripts: true, method: 'get',  parameters: pars, onComplete:ajax_response});
}

function showSubcats(button,did,evnt) {
    function ajax_response(resp) {
        showbox('new');
    }
    var url ="/ajax";
    var pars ="a=dsubcats&b="+button+"&d="+did;
    var target = "innerbox";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function subcatForm(subId) {
    var nodes = document.getElementsByName("cats[]");
    var c = 0;
    var i;
    for(i = 0;i < nodes.length;++i) {
       if (nodes[i].checked == true) {
          c = c + 1;
       }
    }
    if (c == 4) {
      for(i = 0;i < nodes.length;++i) {
         if (nodes[i].checked == true && nodes[i].disabled == false && nodes[i].value != subId) {
            nodes[i].checked = false;
            break;
         }
      }
    }
    var url ="/ajax";
    var pars ="a=subform&cid="+subId;
    var target = "subcategory";
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars});
}


function updateFooterC(cid,pid) {
        document.getElementById('province_list').innerHTML = "";
        document.getElementById('district_list').innerHTML = "";
        setFooterC(cid);
        setFooterP('-1',cid);
}

function setFooterC(cid) {
    function ajax_response(resp) {
        //setFooterDistricts(prvnc,dist);
    }
    var url = '/ajax';
    var pars = 'a=clist&c='+cid;
    var target = 'country_list';
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function updateFooterP(pid,cid) {
        document.getElementById('district_list').innerHTML = "";
        setFooterP(pid,cid);
        setFooterD('-1',pid);
}

function setFooterP(pid,cid) {
    function ajax_response(resp) {
       // setFooterDistricts(prvnc,dist);
    }
    var url = '/ajax';
    var pars = 'a=plist&p='+pid+'&c='+cid;
    var target = 'province_list';
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function setFooterD(did,pid) {
    var url = '/ajax';
    var pars = 'a=dlist&d='+did+'&p='+pid;
    var target = 'district_list';
    var myAjax = new Ajax.Updater(target, url, {  method: 'get',  parameters: pars});
}


//Delete from list of advertisers in admin panel
function delAdvList() {
    function ajax_response(resp) {}
    var nodes = document.getElementsByName('selAdv[]');
    var c = 0;
    var newpars = "";
    for (i = 0;i < nodes.length;++i) {
        if (nodes[i].checked == true) {
            newpars = newpars + "&"+c+"="+nodes[i].value;
            document.getElementById('a_'+nodes[i].value).style.display = 'none';
            c = c + 1;
        }
    }
    var url = '/ajax';
    var pars = 'delAdv=1'+newpars;
    var target = 'main';
    var myAjax = new Ajax.Request( url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

//Delete from list of agents in admin panel
function delAgentList() {
    function ajax_response(resp) {}
    var nodes = document.getElementsByName('selAdv[]');
    var c = 0;
    var newpars = "";
    for (i = 0;i < nodes.length;++i) {
        if (nodes[i].checked == true) {
            newpars = newpars + "&"+c+"="+nodes[i].value;
            document.getElementById('a_'+nodes[i].value).style.display = 'none';
            c = c + 1;
        }
    }
    var url = '/ajax';
    var pars = 'delAgent=1'+newpars;
    var target = 'main';
    var myAjax = new Ajax.Request( url, {  method: 'get',  parameters: pars, onComplete:ajax_response});
}

function agentBForm(opt) {
   if (opt == 0) {
      var dtype = "none";
      $('busType').innerHTML = "Business";
   }
   if (opt == 1) {
      var dtype = "block";
      $('busType').innerHTML = "Brokerage";
   }
   document.getElementById('hid1').style.display = dtype;
   document.getElementById('hid2').style.display = dtype;
   document.getElementById('hid3').style.display = dtype;
   document.getElementById('hid4').style.display = dtype;
}
