function jump2(id, s) {
  var val = document.getElementById(id).value;
  document.location.href=val + "&s=" + s;
}

function popup(url) {
  window.open(url, "popup", "height=400,width=600,scrollbars=1,resizable=0,status=0,toolbar=0,location=0,menubar=0,menubar=0");
}

function changeUpdateTime( campaignId ) {
  var _updateTime = document.getElementById("_update_interval").value * 1000;
  alert(_updateTime);
}

function selectOption(adTypeId, adSizeId) {
  var element = document.getElementById("sizeId[" + adTypeId + "]");
  for ( var i = 0; i < element.length; i++ ) {
    if ( element.options[i].value == adSizeId ) {
      element.selectedIndex = i;
    }
  }
}

function saveLoginInfo(form) {
  if ( form.saveLogin.checked == true ) {
    addCookie("_USERNAME", form.emailaddress.value);
    addCookie("_PASSWORD", form.password.value);
    addCookie("_SAVEPASSWORD", "1");
  } else {
    deleteCookie("_USERNAME");
    deleteCookie("_PASSWORD");
    deleteCookie("_SAVEPASSWORD");
  }
}  
       
function getLoginInfo() {
  if (eval(getCookie("_SAVEPASSWORD"))) {
    form = document.getElementById("formLogin");
    form.emailaddress.value = getCookie("_USERNAME");
    form.password.value = getCookie("_PASSWORD");
    form.saveLogin.checked = true;
  }
}

function addCookie(tag, value) {
  var expireDate = new Date();
  var expireString = "";
  expireDate.setTime(expireDate.getTime() + (1000 * 60 * 60 * 24 * 30));
  expireString = "expires=" + expireDate.toGMTString();
  document.cookie = tag + "=" + escape(value) + ";" + expireString + ";";
}

function deleteCookie(tag) {
  addCookie(tag, "");
}

function getCookie(tag) {
  var value = null;
  var myCookie = document.cookie + ";";
  var findTag = tag + "=";
  var endPos;

  if (myCookie.length > 0) {
    var beginPos = myCookie.indexOf(findTag);
    if (beginPos != -1) {
      beginPos += findTag.length;
      endPos = myCookie.indexOf(";", beginPos);
      if (endPos == -1)
        endPos = myCookie.length;
      value = unescape(myCookie.substring(beginPos, endPos));
    }
  }
  return value;
}

function getFormElements ( form ) {
  var allFormElements = "";
  for ( var lengthOfForm = 0; lengthOfForm < form.elements.length; lengthOfForm++ ) {
    var element = form.elements[lengthOfForm];
    switch ( element.type ) {
      case "select-multiple":
        for ( var lengthOfSelect = 0; lengthOfSelect < element.options.length; lengthOfSelect++ ) {
          if ( element.options[lengthOfSelect].selected ) {
            allFormElements += element.name + "=" + encodeURIComponent(element.options[lengthOfSelect].value) + "&";
          }
        }
        break;
      case "checkbox":
        if ( element.checked ) {
          allFormElements += element.name + "=" + encodeURIComponent(element.value) + "&";
        } else {
          allFormElements += element.name + "=0&";
        }
        break;
      case "radio":
        if ( element.checked ) {
          allFormElements += element.name + "=" + encodeURIComponent(element.value) + "&";
        } 
        break;
      default:
        allFormElements += element.name + "=" + encodeURIComponent(element.value) + "&";
        break;
    }
  }
  return allFormElements;
}

function createElement ( form, name, value ) {
  var element = document.createElement("input");
      element.type = "hidden";
      element.name = name;
      element.id = name;
      element.value = value;
      element.style.display = "none";
  form.appendChild(element);
}

function jumpTo ( thisId, nextId, max ) {
  if ( document.getElementById(thisId).value.length == max ) {
    if ( nextId ) {
      document.getElementById(nextId).focus();
    }
  }
}

function getNextHighestZindex(obj){   
  var highestIndex = 0;   
  var currentIndex = 0;   
  var elArray = Array();   
  if (obj){ elArray = obj.getElementsByTagName('*'); }else{ elArray = document.getElementsByTagName('*'); }   
  for(var i=0; i < elArray.length; i++){   
    if (elArray[i].currentStyle){   
      currentIndex = parseFloat(elArray[i].currentStyle['zIndex']);   
    }else if(window.getComputedStyle){   
      currentIndex = parseFloat(document.defaultView.getComputedStyle(elArray[i],null).getPropertyValue('z-index'));   
    }   
    if(!isNaN(currentIndex) && currentIndex > highestIndex){ highestIndex = currentIndex; }   
  }   
  return(highestIndex+1);   
}  

function grayOut(vis, divContent, options) {
  window.scrollTo(0,0);
  var options = options || {}; 
  var zindex = getNextHighestZindex(document);
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           
        tnode.style.position='absolute';                 
        tnode.style.top='0px';                           
        tnode.style.left='0px';                          
        tnode.style.overflow='hidden';                   
        tnode.style.display='none';                      
        tnode.id='darkenScreenObject';                   
    tbody.appendChild(tnode);                            
    dark=document.getElementById('darkenScreenObject');  
  }
  if (vis) {
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }
    document.body.style.overflow = "hidden";
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';
    var content = document.getElementById(divContent);
    content.style.zIndex = getNextHighestZindex(document);
    content.style.visibility = "visible";
  } else {
    var content = document.getElementById(divContent);
    content.style.visibility = "hidden";
    document.body.style.overflow = "auto";
    dark.style.display='none';
  }
}

function buildCenterBox (divId, height, width) {
  var _top = 0 - (height / 2);
  var _left = 0 - (width / 2);
  var _div = document.getElementById(divId);
  _div.style.marginTop = _top.toFixed(0);
  _div.style.marginLeft = _left.toFixed(0);
  _div.style.position = "absolute";
  _div.style.top = "50%";
  _div.style.left = "50%";
  _div.style.width = width;
  _div.style.height = height;
  _div.style.visibility = "visible";
  _div.style.background = "#FFFFFF";
  _div.style.color = "#000000";
  _div.style.border = "3px double black";
  _div.style.padding = "10px";
  _div.style.overflow = "hidden";
}

function JSONscriptRequest(fullUrl) {
  this.fullUrl = fullUrl; 
  this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
  this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
  this.headLoc = document.getElementsByTagName("head").item(0);
}

JSONscriptRequest.scriptCounter = 1;

JSONscriptRequest.prototype.buildScriptTag = function () {
  this.scriptObj = document.createElement("script");
  this.scriptObj.setAttribute("type", "text/javascript");
  this.scriptObj.setAttribute("charset", "utf-8");
  this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE + "&scriptId=" + this.scriptId);
  this.scriptObj.setAttribute("id", this.scriptId);
}
 
JSONscriptRequest.prototype.removeScriptTag = function ( scriptId ) {
  if ( myObj = document.getElementById(scriptId) ) {
    this.headLoc.removeChild(myObj);  
  }
}

JSONscriptRequest.prototype.addScriptTag = function () {
  this.headLoc.appendChild(this.scriptObj);
}

function selectAll(id) {
  document.getElementById(id).focus();
  document.getElementById(id).select();
  return false;
}

function check_boxes (form, id, name) {
  for ( var i = 0; i < form.elements.length; i++ ) {
    if ( form.elements[i].name == name ) {
      form.elements[i].checked = document.getElementById(id).checked;
    }
  }
}

function gotoPage(pageId, element, extraInfo) {
  if ( ! extraInfo ) { extraInfo = ""; }
  var ID = document.getElementById(pageId).value;
  document.location.href="?" + extraInfo + element + "=" + ID;
}

function getDomainInfo () {
  var fullurl = document.URL;
      fullurl = fullurl.replace(/\?.*$/, "");
      fullurl = fullurl.replace(/^http:\/\/|https:\/\/|ssl:\/\//, '');
  var urlparts = fullurl.split('/');
  var domain = urlparts[0];
  var filename = urlparts[urlparts.length - 1];
  var dirpath = "/";
  for ( var i = 1; i < urlparts.length - 1; i++ ) {
    dirpath = dirpath + urlparts[i] + "/";
  }
  var domainInfo = {"domain" : domain, "file" : filename, "dir" : dirpath};            
  return domainInfo;
}

function edit_user ( id ) {
  domainInfo = getDomainInfo();
  request = "http://" + domainInfo['domain'] + domainInfo['dir'] + "admin.php?callback=_edit_user&id=" + id;
  aObj = new JSONscriptRequest(request);
  aObj.buildScriptTag();
  aObj.addScriptTag();  
  return false;
}

function _edit_user (jsonData) {
  document.getElementById("userbox").innerHTML = jsonData.content;
  buildCenterBox("userbox", 500, 500);
  document.getElementById("userbox").style.overflow = "scroll";
  grayOut(true, "userbox");
  aObj.removeScriptTag(jsonData.scriptId);
}

function processForm ( form, action, button ) {

  var allFormElements = "";
  for ( var lengthOfForm = 0; lengthOfForm < form.elements.length; lengthOfForm++ ) {
    var element = form.elements[lengthOfForm];
    switch ( element.type ) {
      case "checkbox":
        if ( ! element.checked ) {
          form.elements[lengthOfForm].checked = 1;
          form.elements[lengthOfForm].value = 0;
        }
        break;
    }
  }

  ajaxOBJ = function() {
    this.onFailure = function() { alert("Couldn't Process Form.  Please try again later"); }
    this.OnSuccess = function() {
      var response = this.GetResponse();
      if ( response[0] == "Success" ) {
        if ( response[1] != "" ) {
          eval(response[1]);
        }
        if ( response[2] ) {
          document.location.href = response[2];
        }
        return false;
      }
      alert(response[2]);
      grayOut(false, "please_wait");
      if ( button ) {
        button.value = submitValue;
        button.disabled = false;
      } else {
        document.getElementById('submit').value = submitValue;
        document.getElementById('submit').disabled = false;
      }
    }
  }

  domainInfo = getDomainInfo();
  var match = domainInfo['dir'].match(/Admin/);
  if ( match ) {
    loadIMG = "http://" + domainInfo['domain'] + domainInfo['dir'] + "../images/loading.gif";
  } else {
    loadIMG = "http://" + domainInfo['domain'] + domainInfo['dir'] + "images/loading.gif";
  }

  var div = document.createElement('div');
      div.id = div.name = "please_wait";
      div.style.height = div.style.width = 100;
      div.style.overflow = div.style.visibility = "hidden";
      div.style.display = "inline";
      div.innerHTML = '<div><img style="vertical-align:middle;" src="' + loadIMG + '">Please Wait</div>';
  document.body.appendChild(div);

  buildCenterBox("please_wait", 70, 200);
  grayOut(true, "please_wait");

  createElement(form, "_action", action);
  if ( form.enctype == "multipart/form-data" ) {
    var nameId = build_uploader();
    form.target = "iframe_" + nameId;
    createElement(form, "divId", "div_" + nameId);
    form.submit.value = " ... File Uploading ... ";
    form.submit.disabled = true;
    return true;
  }

  ajaxOBJ.prototype = new ajax_lib();
  ajax = new ajaxOBJ;

  if ( button ) {
    button = document.getElementById(button);
    var submitValue = button.value;
    button.value = "... Processing ...";
    button.disabled = true;
  } else {
    var submitValue = document.getElementById('submit').value;
    document.getElementById('submit').value = "... Processing ...";
    document.getElementById('submit').disabled = true;
  }

  var formElements = getFormElements(form);
  if ( form.method == "post" ) {
    ajax.post(form.action, formElements);
  } else {
    var url = form.action;
    ajax.get(url);
  }
  return false;
}

function processSearchForm ( form ) {
  ajaxOBJ = function() {
    this.onFailure = function() { alert("Couldn't Process Form.  Please try again later"); }
    this.OnSuccess = function() {
      document.getElementById('submit').value = "Search";
      document.getElementById('submit').disabled = false;
      document.getElementById('searchresults').innerHTML = this.GetResponseText();
      Tabs.GoTo("results");
    }
  }
  ajaxOBJ.prototype = new ajax_lib();
  ajax = new ajaxOBJ;
  document.getElementById('submit').value = "... Processing ...";
  document.getElementById('submit').disabled = true;
  var formElements = getFormElements(form);
  ajax.post("search.php", formElements);
  return false;
}

function pull_logs ( campaignId ) {
  //setTimeout('hideAd(\''+ campaignId +'\')', (document.getElementById("_update_interval").value * 1000));
  download_page("campaign_manager.php?get=getTrafficLogs&id=" + campaignId, "trafficLogContent");
}

function download_library ( adId ) {
  download_page("advertisements.php?get=library&id=" + adId, "aelib");
}

function viewCampaignAdStats ( campaignAdId ) {
  download_page("campaign_manager.php?get=getAdStats&id=" + campaignAdId, "getAdsBox");
  buildCenterBox("getAdsBox", 500, 500);
  grayOut(true, "getAdsBox");
}

function download_page (url, divId) {
  ajaxOBJ = function() {
    this.onFailure = function() { alert("Couldn't Process Form.  Please try again later"); }
    this.OnSuccess = function() {
      document.getElementById(divId).innerHTML = this.GetResponseText();
    }
  }
  ajaxOBJ.prototype = new ajax_lib();
  ajax = new ajaxOBJ;
  ajax.get(url)
}

function memory_upload_complete(formId, divId, message, error) {
  var form = document.getElementById(formId);
  form.submit.value = "Submit Form";
  form.submit.disabled = false;
  alert(message);
  if ( error == '0' ) { document.location.href="memory.php"; }
  id = document.getElementById(divId);
  document.body.removeChild(id);
  grayOut(false, "please_wait");
}


function product_upload_complete(formId, divId, message, error) {
  var form = document.getElementById(formId);
  form.submit.value = "Submit Form";
  form.submit.disabled = false;
  alert(message);
  if ( error == '0' ) { document.location.href = "inventory.php"; return false; }
  id = document.getElementById(divId);
  document.body.removeChild(id);
  grayOut(false, "please_wait");
}

function packaging_upload_complete(formId, divId, message, error) {
  var form = document.getElementById(formId);
  form.submit.value = "Submit Form";
  form.submit.disabled = false;
  alert(message);
  if ( error == '0' ) { document.location.href="packaging.php"; }
  id = document.getElementById(divId);
  document.body.removeChild(id);
  grayOut(false, "please_wait");
}

function accessory_upload_complete(formId, divId, message, error) {
  var form = document.getElementById(formId);
  form.submit.value = "Submit Form";
  form.submit.disabled = false;
  alert(message);
  if ( error == '0' ) { document.location.href="accessories.php"; }
  id = document.getElementById(divId);
  document.body.removeChild(id);
  grayOut(false, "please_wait");
}

function upload_complete(formId, divId, message, divid2, filename) {
  var form = document.getElementById(formId);
  form.submit.value = "Upload File(s)";
  form.submit.disabled = false;
  if ( document.getElementById("rin_uploader") ) {
    document.getElementById("rin_uploader").value = "";    
  }
  id = document.getElementById(divId);
  document.body.removeChild(id);
  alert(message);
  grayOut(false, "please_wait");
}

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

function build_uploader () {
  var nameId = gen_name();
  var div = document.createElement('div');
      div.id = div.name = "div_" + nameId;
      div.style.height = div.style.width = 400;
      div.style.overflow = div.style.visibility = "hidden";
      div.style.display = "inline"; 
      div.innerHTML = '<iframe id="iframe_' + nameId + '" name="iframe_' + nameId + '"></iframe>';
  document.body.appendChild(div);
  var element = document.getElementById("iframe_" + nameId);
  try {
    element.addEventListener('load', function() {}, false);
  } catch ( error ) {
    element.attachEvent('onload', function() {});
  }
  return nameId;
}

function viewHTML (id) {
  var div = document.createElement('div');
      div.id = div.name = "div_viewHTML";
      div.style.overflow = "auto";
  var html = document.getElementById(id).innerHTML;
      html = html.replace(/&lt;/g, "<");
      html = html.replace(/&gt;/g, ">");
  var extraHTML = "<center><input type=\"button\" name=\"close\" value=\"Close\" onClick=\"closeHTML();\"></center>";
  div.innerHTML = "<div>" + extraHTML + html + "</div>";
  document.body.appendChild(div);
  buildCenterBox("div_viewHTML", 600, 800);
  grayOut(true, "div_viewHTML");
}

function closeHTML () {
  grayOut(false, "div_viewHTML");
  var id = document.getElementById("div_viewHTML");
  document.body.removeChild(id);
}

function update_adsizes () {
  download_page("admin.php?get=adSizes", "adsizes_content");
}

function select_remove ( element ) {
  for ( var i = 0; i < element.length; i++ ) {
    if ( element.options[i].selected ) {
      element.remove(i);
      select_remove(element);
    }
  }
}

function select_all_items ( elementId ) {
  var element = document.getElementById(elementId);
  for ( var i = 0; i < element.options.length; i++ ) {
    element.options[i].selected = true;
  }
}

function select_move_item(fromId, toId) {
  var fromSelect = document.getElementById(fromId);
  var toSelect = document.getElementById(toId);

  for ( var i = 0; i < fromSelect.length; i++ ) {
    if ( fromSelect.options[i].selected ) {
      var txt = fromSelect.options[i].text;
      var val = fromSelect.options[i].value;
//      var opt = document.createElement("option");
//          opt.text = txt;
//          opt.value = val;
//      toSelect.appendChild(opt);
        toSelect.options[toSelect.options.length] = new Option(txt, val);
    }
  }
  select_remove(fromSelect);
  select_sort(toSelect);
  select_sort(fromSelect);
  return false;
}

function select_move_all (fromId, toId) {
  var fromSelect = document.getElementById(fromId);
  var toSelect = document.getElementById(toId);
  for ( var i = 0; i < fromSelect.options.length; i++ ) {
    if ( fromSelect.options[i].value ) {
      var txt = fromSelect.options[i].text;
      var val = fromSelect.options[i].value;
//      var opt = document.createElement("option");
//          opt.text = txt;
//          opt.value = val;
//      toSelect.appendChild(opt);
      toSelect.options[toSelect.options.length] = new Option(txt, val);

    }
  }
  select_all_items(fromId);
  select_remove(fromSelect);
  select_sort(toSelect);
  return false;
}

function select_sort(element) { 
  var arrTexts = new Array(); 
  var arrValues = new Array(); 
  var arrOldTexts = new Array(); 
  for( var i = 0; i < element.options.length; i++) { 
    arrTexts[i] = element.options[i].text; 
    arrValues[i] = element.options[i].value; 
    arrOldTexts[i] = element.options[i].text; 
  } 
  arrTexts.sort(); 
  for( var i = 0;  i < element.options.length; i++) { 
    element.options[i].text = arrTexts[i]; 
    for(var j = 0; j < element.options.length; j++) { 
      if (arrTexts[i] == arrOldTexts[j]) { 
        element.options[i].value = arrValues[j]; 
        j = element.options.length; 
      }
    } 
  } 
}

function download_report (CID, REPORT) {
  var div = document.createElement("div");
      div.id = "reportoutput";
      div.innerHTML = "Please Wait a Moment";
  document.body.appendChild(div);
  buildCenterBox("reportoutput", 600, 800);
  div.style.display = "block";
  div.style.overflow = "auto";
  download_page("reports.php?report=" + REPORT + "&campaignId=" + CID, "reportoutput");
  grayOut(true, "reportoutput");
}

function close_report() {
  var div = document.getElementById("reportoutput");
  document.body.removeChild(div);
  document.getElementById("darkenScreenObject").style.display = "none";
  document.body.style.overflow = "auto";
}

function getPosition (obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
  }
  return [curleft,curtop];
}

function tooltips ( tooltips ) {
  for ( key in tooltips ) {
    if ( document.getElementById(key) ) {

      var div_tooltip = "tooltip_" + key;

      var element = document.getElementById(key);
          element.onfocus = function() {
            var id = "tooltip_" + this.id;
            var div = document.getElementById(id);
                div.style.display = "block";
          }
          element.onmouseover = element.onfocus;
          element.onblur = function() {
            var id = "tooltip_" + this.id;
            var div = document.getElementById(id);
                div.style.display = "none";
          }
          element.onmouseout = element.onblur;

      var pos = getPosition(element);

      var div = document.createElement("div");
          div.id = div_tooltip;
          div.style.width = 200;
          div.style.zIndex = getNextHighestZindex();
          div.style.top = pos[1];
          div.style.left = (element.offsetWidth + pos[0]) + 5;
          div.style.position = "absolute";
          div.style.display = "none";
          div.style.border = "1px solid black";
          div.style.padding = 5;
          div.style.background = "yellow";
          div.innerHTML = tooltips[key];
      document.getElementById("tooltips").appendChild(div);

    }
  }
}

function displayAd(id, type) {
  var div = document.createElement("div");
      div.id = "rin_displayAd";
      div.style.zIndex = getNextHighestZindex();
      div.style.height = document.body.offsetHeight;
      div.style.width = document.body.offsetWidth;
      div.style.background = "white";
      div.style.position = "absolute";
      div.style.top = 0;
      div.style.left = 0;
      div.style.display = "block";
      div.style.overflow = "auto";
      div.innerHTML = "<div style='padding-top:50px;'><center><b>Please wait while the ad loads</b></center></div>";
  document.body.appendChild(div);
  download_page("campaign_manager.php?get=displayAd&type=" + type + "&id=" + id, "rin_displayAd");
  return false;
}

function closeDisplayAd() {
  var div = document.getElementById("rin_displayAd");
  document.body.removeChild(div);
}

      function closeWINDOW(divId) {
        if ( RELOADWINDOW == 0 ) {
          grayOut(false, divId);
        } else {
          window.location.reload();
        }
      }

      function load_page ( page, func, divId, id ) {
        domainInfo = getDomainInfo();
        var data = "function=" + func +
                   "&divId=" + divId +
                   "&id=" + id +
                   "&callback=_load_page";
        request = "http://" + domainInfo['domain'] + domainInfo['dir'] + page + "?" + data;
        aObj = new JSONscriptRequest(request);
        aObj.buildScriptTag();
        aObj.addScriptTag();
        document.getElementById(divId).innerHTML = " .. loading ..";
        buildCenterBox(divId, 500, 500);
        document.getElementById(divId).style.overflow = "scroll";
        grayOut(true, divId);
        return false;
      }

      function _load_page (jsonData) {
        var divId = jsonData.divId;
        document.getElementById(divId).innerHTML = jsonData.content;
        // buildCenterBox(divId, 500, 500);
        // document.getElementById(divId).style.overflow = "scroll";
        // grayOut(true, divId);
        aObj.removeScriptTag(jsonData.scriptId);
      }


