var ajax_active = 0; //1 at a time please.
var current_quotebubble_active = 'none'; //what quote buble should appear next (hovering on?)
var current_quotebubble_showing = 'none'; //what icon's quotebox is already showing?
var newest_z_index = 5; //keep track of the highest layer
var open_subtab = '';
open_about_box = ''; 
Ajax.Responders.register({
  onCreate: function(request, transport) {
    if($('busy') && Ajax.activeRequestCount>0)
      Effect.Appear('busy',{duration:0.5,queue:'end'});
     //new Insertion.Bottom('debug', '[' + new Date().toString() + '] accessing ' + request.url + '<br/>')
     request['timeoutId'] = window.setTimeout(
      function() {
      // If we have hit the timeout and the AJAX request is active, abort it and let the user know
      if (request.transport.readyState == 1 || request.transport.readyState == 2 || request.transport.readyState == 3) {
        request.transport.abort();
        showFailureMessage();
        // Run the onFailure method if we set one up when creating the AJAX object
        if (request.options['onFailure']) {
          request.options['onFailure'](request.transport, request.json);
        }
      }
      },
      30000 // Thirty seconds
     );

  },
  onComplete: function(request) {
    urchinTracker('/ajax' + request.url);
    if($('busy') && Ajax.activeRequestCount==0) {
      Effect.Fade('busy',{duration:0.3,queue:'end'});
    }
    window.clearTimeout(request['timeoutId']);
  }

});

Object.extend(Ajax.Request.prototype,  {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
    if (this.options["parameters"] != '') {
      this.options["parameters"] += '&';
    }
    this.options["parameters"] += 'a_t=' + $F('a_t');
  }
}
);


function showFailureMessage() {
  alert('Sorry, your request could not be completed!');
}


function $F2(formname, fieldname) {
  return document.forms[formname].elements[fieldname];
}
function radioValue(r){
  if (r.checked == true) {
    return r.value;
  }
    for (x = 0; x < r.length; x++)
    {
        if (r[x].checked == true) return r[x].value;
    }
    return '';
}
function n2p(n){
  return '('+n.substring(0,3)+') '+n.substring(3,6)+'-'+n.substring(6,10);
}
function p2a(n) {
  return new Array(n.substring(1,4), n.substring(6,9), n.substring(10,14));
}

function autohop(e, x,size,to) {
  if (!e) var e = window.event;
  keycode = e.keyCode;

  if ( keycode == 9 || keycode == 16 || keycode == 36 || keycode == 37 || keycode == 39 || keycode == 46) {
    return;
  }
  if (x.value.length == size) {
    Try.these( function() {
                Field.focus(to);
               },
               function() {
               document.form.element[to].focus();
               } );
  }
}
function toggleSelectBoxes(panel, option) {
  selectboxes = $A($(panel).getElementsByTagName("select"));
  iframes = $A($(panel).getElementsByTagName("iframe"));
  objs = $A($(panel).getElementsByTagName("object"));
  if(option == 'hide') {
  selectboxes.each ( function (box, i) {
        Element.hide(box);
  });
  iframes.each ( function (box, i) {Element.hide(box);} );
  objs.each ( function (box, i) {Element.hide(box);} );
  } else {
    selectboxes.each ( function (box, i) {
        Element.show(box);
    });
    iframes.each ( function (box, i) {Element.show(box);} );
    objs.each ( function (box, i) {Element.show(box);} );
  }
};
// fix memory leak on anonymous functions
// http://laurens.vd.oever.nl/weblog/items2005/closures/
Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};

close_lightbox = function(x) {
  $('overlay').style.display = 'none';
  $(x).style.display = 'none';
  return false;
}

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
var getPageSize= function(){
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }

    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    return arrayPageSize;
}

function addLightboxMarkup() {

    bod 				= document.getElementsByTagName('body')[0];
    overlay 			= document.createElement('div');
    overlay.id			= 'overlay';
  bod.insertBefore(overlay, bod.firstChild);
}

function startupLightBox() {
   bod = document.getElementsByTagName('body')[0];
   /* xandy = Element.getDimensions(bod); */
   var arrayPageSize = getPageSize();
   $('overlay').style.top = '0';
     $('overlay').style.left = '0';
   $('overlay').style.height = (arrayPageSize[1] + 'px');
   /* $('overlay').style.width = xandy['width'] + 'px'; */
   $('overlay').style.width = '100%';
   $('overlay').style.display = 'block';
}

function repositionLightBoxes() {
   var lightboxes = $A(document.getElementsByClassName('lightbox'));
   var aps = getPageSize();
   lightboxes.each(
     function(lb) {
       xandy = Element.getDimensions(lb);
       lb.style.left = ((aps[0]-xandy['width'])/2) + 'px';
     }
   )
}


function setVal(objID, selIndex) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = selIndex;
}
function stopProp(e) {
  Try.these( function() { e.cancelBubble=true; e.stopPropagation(); e.preventBubble();});
}
function getReverseDirection(value) {
  if (value == 'asc') {
    return 'desc';
  } else {
    return 'asc';
  }
}


function setQuickRule(dnd, temp_number) {
  new Ajax.Request("/profiles/set_quick_rule", {parameters : "do_not_disturb=" + dnd + "&temporary_number=" + temp_number});
}

function show_call_dialog(ani) {
  new Ajax.Request("/calls/show_call_dialog", { parameters : 'ani=' + ani + '&calltype=call'});
}
function show_record_dialog(category_id) {
  new Ajax.Request("/calls/show_call_dialog", { parameters : 'category_id=' + category_id + '&calltype=record' } );
}
function show_record_name_dialog() {
  new Ajax.Request("/calls/show_call_dialog", { parameters : 'calltype=name' } );
}

function createCall(destno, ani) {
  //if (!ani.match(/^(\d{10})$/) || !destno.match(/^(\d{10})$/)) {
    //$('call_dialog_error_msg').innerHTML = '<img src="/images/icons/icon_error.png" align="center"> Please enter a valid phone number.';
   // return false;
 // }
    new Ajax.Request("/calls/send_call_request", {parameters : 'calltype=call&destno=' + destno + '&ani=' + ani } );
}

function cancelCall(call_type) {
  new Ajax.Request("/calls/send_cancel_request");
}

function cancelGreeting() {
  new Ajax.Request("/calls/send_cancel_request/?type=greeting");
}

function hangupCall(call_type) {
  new Ajax.Request("/calls/send_cancel_request/?type=" + call_type);
}

function closeCallBox(call_type) {
  if (call_type == 'call' ) {
    closeGreetingRecordBox();
  } else if (call_type == 'ani_greeting') {
    closeAniGreetingBox();
  } else if (call_type == 'record') {
    closeGreetingRecordBox();
  } else if (call_type == 'name') {
    closeNameRecordBox();
  }    

}

/* new one when the new quick call is placed in here */
/*function quickCallResize(hght) {
  $('quick_call').style.height = hght + "px";
  $('quick_call_container').style.height =  hght + "px";
}
*/


playStopPlaya = function (id) {

  if (Playa.state == Playa.STATE_PLAYING && Playa.surl == id) {
    Playa.doStop();
  }
  else if (Playa.surl == '') {
    Playa.surl =  id;
    Playa.doPlayUrl(id);
  } else if (Playa.surl !=  id) {
    Playa.onPlayStop();
    Playa.surl =  id;
    Playa.doPlayUrl(id);
  } else {
    Playa.doPlay();
  }
}

var mousexclick = 0;
var mouseyclick = 0;

startClick = function(e) {
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)
    {
        mousexclick = e.pageX;
        mouseyclick = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        mousexclick = e.clientX + document.body.scrollLeft;
        mouseyclick = e.clientY + document.body.scrollTop;
    }
}

stopClick = function(e, url) {
  var posx = 0;
  var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)
    {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        posx = e.clientX + document.body.scrollLeft;
        posy = e.clientY + document.body.scrollTop;
    }
  if (Math.abs(posx - mousexclick) < 3 && Math.abs(posy - mouseyclick) < 3) {
    if (typeof(url) == 'function') {
      url();
    } else {
    window.location.href=url;
    }
  }

}


if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(suffix) {
    var startPos = this.length - suffix.length;
    if (startPos < 0) {
      return false;
    }
    return (this.lastIndexOf(suffix, startPos) == startPos);
  };
}

function getDragElement(element){
  if (element.id.endsWith('_dragged') == true ) {
    return false;
  }
    var el = element.cloneNode(true);
    el.id = element.id + "_dragged";
    el.onmouseover = null;

    //Element.removeClassName(el, 'category_contact_name');
    //Element.addClassName(el, 'border_orange');
    //console.log('%s', Element.classNames(el));
    document.body.appendChild(el);
    //or document.body..appendChild(el), but I used some div in tree to keep element CSS classes work
    /*if( MANY ){
        el.innerHTML = "[" + MANY_N + " elements]";
    }*/
    return el;
}

changeGroupTab = function(obj) {
 var sel_element = $A(document.getElementsByClassName("sel", obj.parentNode)).first();
 Element.removeClassName(sel_element, 'sel');
 Element.addClassName(obj, 'sel');
}

function openDialog()
{
if (window.showModalDialog) {
 window.showModalDialog("../tos.html","","status:no;dialogWidth:750px;dialogHeight:500px;help:no;scroll:yes" );
} else {
 window.open('../tos.html','name',
'height=500,width=750,left=300,top=100,toolbar=no,directories=no,status=no,previous linemenubar=no,scrollbars=yes,resizable=no,modal=yes');
}
}

function openDialog1()
{
if (window.showModalDialog) {
window.showModalDialog("../eula.html","","status:no;dialogWidth:500px;dialogHeight:300px;help:no;scroll:yes" );
} else {
window.open('../eula.html','name',
'height=300,width=500,left=300,top=100,toolbar=no,directories=no,status=no,previous linemenubar=no,scrollbars=yes,resizable=no,modal=yes');
}
}

function openpopup() {
 var popurl="../../projectcare/ktvu.html"
 winpops=window.open(popurl,"","width=390,height=340,scrollbars,")
}

function changeEffect(id) {
 $(id).className = 'chg_news_bkgrnd';
}

function revChangeEffect(id) {
 $(id).className = 'decrnone';
}

function premium_popup() {
  Element.show('premium_upgrade_div');
  scroll(0,0);
}

function getCookie(c_name)
{
  if (document.cookie.length>0)
  {
    c_start=document.cookie.indexOf(c_name + "=")
    if (c_start!=-1)
    {
      c_start=c_start + c_name.length+1
      c_end=document.cookie.indexOf(";",c_start)
      if (c_end==-1) c_end=document.cookie.length
      return unescape(document.cookie.substring(c_start,c_end))
    }
  }
  return ""
}

function getSessionCookie() {
  return getCookie("_session_id");
}

function getBrowser() {
  if (navigator.userAgent.indexOf("MSIE") != -1) {
    return 1;
  }
  else {
    return 0;
  }
}

function showMore(tmId) {
  Element.hide("tm"+tmId);
  Element.show("tmdetls"+tmId);
}    

function showMonthlyTMs(month) {
   if(open_about_box != '') {
     Element.setStyle(open_about_box, {background:''} ); 
   }
   open_about_box = month;
   new Ajax.Request('/home/showmonthlytms?month='+month, {asynchronous:true, evalScripts:true } );
}        

