/*
 * Limit numbers of chars in a textarea/input field
 * Params:
 *   textId: id of text field
 *   displayId: id of field where character count is displayed
 *   max: max number of allowed characters
 */
function charLimit(textId,displayId,max) {
  var textField = dojo.byId(textId);
  var typed = textField.value.length;
  var displayField = dojo.byId(displayId);
  displayField.innerHTML = typed;
  if (typed > max) {
    displayField.innerHTML = max;
    textField.value = textField.value.substring(0, max);
  }
}

/*
 * Show/Hide an object based on the value of a form field
 */
function showHideOnValue(valueObjId,displayObjId,showOnValue) {
  var valueObj = dojo.byId(valueObjId);
  var displayObj = dojo.byId(displayObjId);
  var display = (valueObj.value == showOnValue)?'block':'none';
  showHideBlock(displayObjId,display);
}

/*
 *
 */
function hideBlockAll(relativeName) {
  dojo.query('div[id^="'+relativeName+'"]').forEach(function(x) { x.style.display = 'none'});
}

/*
 * Use this to show or hide a block or table row
 * Omit the 'display' parameter to do the opposite of the current display
 */
function showHideBlock(blockId,display) {
  var obj = dojo.byId(blockId);

  if (!obj) { return false; }
  
  var tagName = obj.tagName.toLowerCase();

  //Just do the uppersite if display is omitted
  if (display === undefined) {
    display = (obj.style.display == 'none')?'block':'none';
  }
  
  if (display == 'none') {
    obj.style.display = 'none';
  } else if (display == 'block' && tagName != 'tr') {
    obj.style.display = 'block';
  } else {
    try {
      //Some browsers do not understand 'block' for table rows
      obj.style.display = 'table-row';        
    } catch(e) {
      obj.style.display = 'block';
    }
  }
  return true;
}

function inlineShift(first,second,preserveParentDimensions) {
  if (preserveParentDimensions === undefined) {
  } else if (preserveParentDimensions === true) {
    var w = dojo.byId(first).parentNode.offsetWidth;
    var h = dojo.byId(first).parentNode.offsetHeight;
    dojo.byId(second).parentNode.style.width = w+'px';
    dojo.byId(second).parentNode.style.height = h+'px';
  }
  showHideInline(first);
  showHideInline(second);
}

function blockShiftMulti() {
  if (!arguments.length) {
    return false;
  }
  var i;
  //Show the first and hide the others
  showHideBlock(arguments[0],'block');
  for (i=0; i<arguments.length; i++) {
    if (i > 0) {
      showHideBlock(arguments[i],'none');
    }
  }
}

/*
 * Use this to show or hide an inline element
 * Omit the 'display' parameter to do the opposite of the current display
 */
function showHideInline(inlineId,display) {
  var obj = dojo.byId(inlineId);

  if (!obj) { return false; }
  
  //Just do the uppersite if display is omitted
  if (display === undefined) {
    display = (obj.style.display == 'none')?'inline':'none';
    obj.style.display = display;
  } else if (display == 'none') {
    obj.style.display = 'none';
  } else if (display == 'inline') {
    obj.style.display = 'inline';
  }
  return true;
}

function currencyConvert(value,from,to) {
  var jsnResult = ajaxCall('post', {"action":"currency","value":value,"from":from,"to":to});
  if (typeof jsnResult == 'object') {
    return jsnResult.result;
  }
}

/*
 * This function is used to delay an action, for example 
 * if an action is fired onkeyup, and we want to wait a
 * certain amount of time after the user stops typing,
 * before we command is fired.
 */
var timeoutId = '';
function delayAction(command,msecs) {
  if (timeoutId != '') {
    clearTimeout(timeoutId);
  }
  timeoutId = setTimeout(command,msecs);
}

function zoomImage(id,time,title) {
  var zoomBox = new dijit.Dialog({ title: title, content: '<img src="image.php?id='+id+'&size=full&time='+time+'" style="width:450px;height:338x">'});
  dojo.body().appendChild(zoomBox.domNode);
  zoomBox.startup();
  zoomBox.show();
}

function getScrollOffset() {
  var _window = dojo.global;
  var _document = dojo.doc;
  var top = _window.pageYOffset || _document.documentElement.scrollTop || dojo.body().scrollTop || 0;
  var left = _window.pageXOffset || _document.documentElement.scrollLeft || dojo.body().scrollLeft || 0;
  return {
    top: top,
    left: left,
    offset:{ x: left, y: top }
  };
}

function ajaxCall(strMethod,jsnParams,frmForm) {
  var jsnResult, 
      strUrl = 'ajax.php', 
      strHandle = 'json';

  if (strMethod === undefined) {
    return false;
  }
    
  if (strMethod == 'get') {
    jsnResult = dojo.xhrGet({
      url: strUrl,
      sync:true,
      content: jsnParams,
      load: function(data,ioArgs) {
        return data;
      },
      error: function(data,ioArgs) { return data; },
      handleAs: strHandle,
      headers: {"Content-Type": "application/json"}
    });

  } else if (strMethod == 'post') {
    if (typeof strForm == 'string') {
      strParams = dojo.formToJson(strForm);
    }
    jsnResult = dojo.rawXhrPost({
      url: strUrl,
      sync: true,
      handleAs: strHandle,
      content: jsnParams,
      load: function(data,ioArgs) {
        return data;
      },
      error: function(data,ioArgs) { return data; }
    });
  }
  return eval(jsnResult.results[0]);
}

function translation(strText,strPage) {
  if (strPage === undefined) {
    strPage = '';
  }
  var jsnResult = ajaxCall('post', {"action":"translation","text":strText,"page":strPage});
  if (typeof jsnResult == 'object') {
    return jsnResult.result;
  }
}

function confirmDelete(boxNames, text) {
  var count = 0;  
  dojo.query('input[id^="'+boxNames+'"]').forEach(function(obj) {
    if (obj.checked) {
      count++;
    }
  });
  if (count > 0) {
    return confirm(text);
  } else {
    return false;
  }
  return false;
}
      
      

function newElement(strTag,strClassName,strId,strText) {
  var objElm, strResult;
  objElm = document.createElement(strTag);
  objElm.className = (strClassName === undefined) ? '' : strClassName;
  objElm.id = (strId === undefined) ? new Date().getTime() : strId;
  if (strText === undefined) {
  } else {
    strResult = translation(strText);
    objElm.appendChild(document.createTextNode(strResult));
  }
  return objElm;
}

function effectFlash(strId,intDelay, intDuration,fcnEnd) {
  var obj = dojo.byId(strId), w1, w2;
  if (intDelay === undefined) intDelay = 500;
  if (intDuration === undefined) intDuration = 1000;
  if (fcnEnd === undefined) fcnEnd = function () {};
  
  if (obj.style.display == 'none') {
    w1 = dojo.fx.wipeIn({node:obj, duration:intDuration});
    w2 = dojo.fx.wipeOut({node:obj, delay: intDelay,duration:intDuration, onEnd: fcnEnd});
  } else {
    w1 = dojo.fx.wipeOut({node:obj, duration: intDuration});
    w2 = dojo.fx.wipeIn({node:obj, delay: intDelay,duration:intDuration, onEnd:fcnEnd});
  }
  dojo.fx.chain([w1,w2]).play();
}

function effectPleaseWait(objCaller, strTag, strClassName) {
  var objWait, objParent;
  objWait = newElement(strTag,strClassName,undefined,'please_wait_long');
  if (objCaller === undefined) {
  } else {
    objCaller.style.display='none';
    objParent = objCaller.parentNode;
    objParent.appendChild(objWait);
    ;
  }
  return objWait;
}

function username_availability(mscCaller,strUsername,bolUserId) {
  var intUserId, objCaller, objWait;
  if (typeof mscCaller == 'object') {
    objCaller = mscCaller;
  } else {
    objCaller = dojo.byId(mscCaller);
  }
  if (bolUserId === undefined) {
    intUserId = 0;
  } else {
    intUserId = (bolUserId) ? 1 : 0;
  }
  objWait = effectPleaseWait(objCaller,'div');
  var result = ajaxCall('post',{'action':'username_availability','username':strUsername,'isOwner':intUserId});
  if (result.success == '1') {
    objResult = newElement('div','message');
  } else {
    objResult = newElement('div','error');
  }
  objResult.style.display = 'none';
  objResult.appendChild(document.createTextNode(result.message));
  objCaller.parentNode.appendChild(objResult);
  fcnEnd = function () { objWait.style.display = 'none'; objCaller.style.display = 'inline'};
  effectFlash(objResult.id,undefined,undefined,fcnEnd);
}

function users_online_count(userCountId, guestCountId) {
  if (dojo.byId(userCountId) && dojo.byId(guestCountId)) {
    objUser = dojo.byId(userCountId);
    objGuest = dojo.byId(guestCountId);
    var result = ajaxCall('post',{'action':'users_online_count'});
    if (result.success == '1') {
      objUser.innerHTML = result.message.users;
      objGuest.innerHTML = result.message.guests;
    }
  }
}

function flashAMessage(displayBox,text,type,fcnEnd) {
  var div, box, objWait;
  if (typeof displayBox == 'object') {
    box = displayBox;
  } else {
    box = dojo.byId(displayBox);
  }
  objWait = effectPleaseWait(box,'div');
  if (type == 'message') {
    div = newElement('div','message');
  } else {
    div = newElement('div','error');
  }
  div.style.display = 'none';
  div.appendChild(document.createTextNode(text));
  box.appendChild(div);
  fcnEnd = function () { objWait.style.display = 'none'; box.style.display = 'inline'};
  effectFlash(box.id,3);
}

function modelStatus(statusName) {
  var result = ajaxCall('post',{'action':'model_edit','onlineStatus':statusName});
}
  
 var MAX_DUMP_DEPTH = 10;

function dumpObj(obj, name, indent, depth) {
  if (depth > MAX_DUMP_DEPTH) {
    return indent + name + ": <Maximum Depth Reached>\n";
  }
  if (typeof obj == "object") {
    var child = null;
    var output = indent + name + "\n";
    indent += "\t";
    for (var item in obj) {
      try {
        child = obj[item];  
      } catch (e) {
        child = "<Unable to Evaluate>";
      }
      if (typeof child == "object") {
        output += dumpObj(child, item, indent, depth + 1);
      } else {
        output += indent + item + ": " + child + "\n";
      }
    }
    return output;
  } else {
    return obj;
  }
}
