utils = {};

/**
* Format bytes to B ,KB, MB,GB
*
* @param Integer bytes
*
* @return String
*/
utils.formatBytes = function(bytes) {
  if( bytes < 1024 ){
    return bytes + ' b';
  }else if( bytes <  1048576 ){
    return Math.round(bytes / 1024) + ' KB';
  }else if( bytes < 1073741824  ){
    return Math.round(bytes / 1048576) + ' MB';
  }else{
    return (Math.round((bytes / 1073741824) * 10) / 10) + ' GB';
  }
}

/**
* Overload function
*/
utils.pleaseLogin = function () {
  alert("Please login.");
};

utils.doRequest = utils.pleaseLogin;

/**
* Get mime type Class
*
* @param String mime
*
* @return String
*/
utils.mimeTypeClass = function(mime) {
  if( !mime || mime == "" ) return "icon";
 
  // Add Content type style Class 
  contentType = {
    "folder"                    : "foldericon",
    "favorite"                  : "iconWs",
    "favoritelocked"            : "iconWslock",
    "text/plain"                : "iconText",
    "application/msword"        : "iconWord",
    "text/html"                 : "iconHTML",
    "application/vnd.ms-excel"  : "iconEXCEL",
    "text/xml"                  : "iconXML",
    "application/xml"           : "iconXML",
    "application/pdf"           : "iconPDF",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "iconWord",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"       : "iconEXCEL",
    "audio/mpeg"                : "iconMPEG",
    "audio/mp3"                 : "iconMPEG",
    "audio/x-mpeg"              : "iconMPEG",
    "audio/x-mp3"               : "iconMPEG",
    "audio/mpeg3"               : "iconMPEG",
    "audio/x-mpeg3"             : "iconMPEG",
    "audio/mpg"                 : "iconMPEG",
    "audio/x-mpg"               : "iconMPEG",
    "audio/x-mpegaudio"         : "iconMPEG",
    "audio/wav"                 : "iconWAVE",
    "audio/wave"                : "iconWAVE",
    "image/jpeg"                : "iconJPG",
    "image/pjpeg"               : "iconJPG",
    "image/bmp"                 : "iconBMP",
    "image/x-ms-bmp"            : "iconBMP",
    "image/png"                 : "iconPNG",
    "image/gif"                 : "iconGIF",
    "video/mpeg"                : "iconVMPEG",
    "video/x-msvideo"           : "iconVMPEG",
    "video/x-flv"               : "iconVMPEG",
    "video/x-ms-wmv"            : "iconVMPEG",
    "video/quicktime"           : "iconVMPEG",
    "audio/ogg"                 : "iconMUSIC",
    "audio/aac"                 : "iconMUSIC",
    "audio/mid"                 : "iconMUSIC",
    "application/x-msdos-program" : "iconEXE",
    "application/zip"           : "iconZIP",
    "application/x-zip-compressed" : "iconZIP",
    "text/comma-separated-values" : "iconCSV",
    "text/csv"                  : "iconCSV"
  }
  
  return ( contentType[mime.toLowerCase()] ? " " + contentType[mime] : "fileicon" );
}

/**
* Get Storage Date and time
*
* @param String storageTime
*
* @return String
*/
utils.getStorageDatetime = function(storageTime) {
  var tokens = storageTime.split("T");
  var dateParts = tokens[0].split("-");
  var timeParts = tokens[1].slice(0, 8).split(":");

  var utc = new Date();
  utc.setDate(1);
  utc.setFullYear(dateParts[0]);
  utc.setMonth(dateParts[1] - 1);
  utc.setDate(dateParts[2]);
  utc.setHours(timeParts[0]);
  utc.setMinutes(timeParts[1]);
  utc.setSeconds(timeParts[2]);

  var local = new Date();
  var utcDate = new Date();
  utcDate.setDate(1);
  utcDate.setFullYear(local.getUTCFullYear());
  utcDate.setMonth(local.getUTCMonth());
  utcDate.setDate(local.getUTCDate());
  utcDate.setHours(local.getUTCHours());
  utcDate.setMinutes(local.getUTCMinutes());
  utcDate.setSeconds(local.getUTCSeconds());
  var hourDiff = Math.round((local - utcDate) / 3600000);
  utc.setHours(utc.getHours() + hourDiff);

  var date = utc;
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  return year + "-" + (month < 10 ? ("0" + month) : month) + "-" + (day < 10 ? ("0" + day) : day) + " " +
         (hour < 10 ? ("0" + hour) : hour) + ":" + (minutes < 10 ? ("0" + minutes) : minutes) + ":" + (seconds < 10 ? ("0" + seconds) : seconds);
}

/**
* Get params from locationSearch
* @param String locationSearch
*
* @return Object
*/
utils.getParamFromLocationSearch = function (locationSearch) {
  if( !locationSearch || locationSearch == "" ) return null;

  var q = locationSearch.slice(1).split("&");

  var params = {};
  for (var i = 0, len = q.length; i < len; i++) {
    var kv = q[i].split("=");
    params[kv[0]] = unescape(kv[1]);
  }

  return params || null;
};

/**
*
* Parse the hash into an object
* @param String hash
*   pattern: [tab{files|webshares|favorites|account}:path]
*            [tab{files|webshares|favorites|account}]
*            [path]
*
* Returns a js object with tab and path attributes.
*/
utils.getParsedHashObject = function (hash) {
  var tokens = hash.replace(/^#/, "").split(":");
  var o = {tab: "", path: ""};
  if( tokens.length > 0 ) {
    if( tokens[0].search(/^files|^webshares|^favorites|^account/) ) {
      o.tab = tokens[0];
    }
    if( tokens.length == 1 ) {
      if( o.tab == "" ) {
        o.path = tokens[0];
      }
    } else {
      o.path = tokens[1];
    }
  }
  return o;
};

/**
* Get params from URL
*
* @param String paramStr
*
* @return Object
*/
utils.getUrlParams = function (paramsStr) {
  if( !paramsStr || paramsStr == "" ) return null;

  paramsStr = paramsStr.substring(paramsStr.indexOf("?")+1);
  var paramsArr = paramsStr.split("&");
  if( paramsArr && paramsArr.length > 0 ) {
    var params = {};
    for( var i = 0 ; i < paramsArr.length ; i++ ) {
      var values = /([^=]+)=(.*)/.exec(paramsArr[i]);
      params[values[1]] = values[2];
    }
    return params;
  }
  return null;
}

/**
* Adds browser class type on body
*/
utils.setBrowserClass = function() {
  var browserClass;
  if( $.browser.msie ) {
    if( $.browser.version == "7.0" ) browserClass = "ie ie7";
    else if( $.browser.version == "8.0" ) browserClass = "ie ie8";
    else if( parseInt($.browser.version) > 8.1 ) browserClass = "ie ie9";
    else browserClass = "ie";
  } else {
    if( $.browser.webkit ) browserClass = "w3c wbk";
    else if( $.browser.mozilla ) browserClass = "w3c ff";
    else if( $.browser.opera ) browserClass = "w3c op";
    else browserClass = "w3c";
  }
  $("body").addClass(browserClass);
}

/**
* Get HTMLDOMNode position
*
* @param HTMLDOMNode elem
* @param String id (optional)
*
* @return Object
*/
utils.getElementPos = function(elem, id) {
  // id is optional 

  var f = ( id && id != "" ? function(elem) { return ( id && id != elem.id ); } : function(elem) { return ( elem.tagName != "BODY" ) ; } );

  var l = 0, t = 0, oc = elem;
  if( elem ) {
    //while ( elem && ( elem.tagName != "BODY" ) ) {
    while( elem && f(elem) ) {
      t += elem.offsetTop || 0;
      l += elem.offsetLeft || 0;
      elem = elem.offsetParent;
    }
    //while ( oc && oc.tagName != "BODY" ) {
    while ( oc && f(oc) ) {
      t -= oc.scrollTop || 0;
      l -= oc.scrollLeft || 0;
      oc = oc.parentNode;
    }
  }
  return { left : l, top : t };
}

/**
* check if x,y position is inside HTMLDOMNode
*
* @param HTMLDOMNode elem
* @param Integer posX
* @param Integer posY
*
* @return Boolean
*/
utils.isInsideElem = function(elem, posX, posY) {
  if( !elem ) return false;

  var mm = this.getElementPos(elem);
  if( mm.left < posX && ( mm.left + elem.offsetWidth ) > posX ) {
    if( mm.top < posY && ( mm.top + elem.offsetHeight ) > posY ) {
      return true;
    }
  }
  return false;
}


/**
* Ellipses on text
* 
* @param String text
* @param Integer width
* @param String style
*
* @return String
*/
utils.ellipses = function(text, width, style) {

  var newElem = window.document.createElement("span");

  // Style - fontSize, fontFamily, lineHeight, fontHeight, letterSpacing
  newElem.style.fontSize    = this.getStyleValue("font-size", style);
  newElem.style.fontFamily  = this.getStyleValue("font-family", style);
  newElem.style.lineHeight  = this.getStyleValue("line-height", style);
  newElem.style.fontWeight  = this.getStyleValue("font-weight", style);
  newElem.style.letterSpacing = this.getStyleValue("letter-spacing", style);

  newElem.style.display = "inline-block";
  newElem.style.whiteSpace = "nowrap";

  newElem.style.top = "0px";
  newElem.style.left = "0px";
  newElem.style.position = "absolute";
  newElem = window.document.body.appendChild(newElem);

  for( var i = 0, len = text.length; i < len; i++ ) {
    if( newElem.clientWidth > ( width - ( parseInt(newElem.style.fontSize, 10) * 4) ) ) {
      text = newElem.innerHTML + "....";
      break;
    }
    newElem.innerHTML += this.getStrAt(text, i);
  }

  newElem.parentNode.removeChild(newElem);

  return text;
}

/**
* Get inline style value
* 
* @param String styleName
* @param String cssText
* 
* @return String
*/
utils.getStyleValue = function(styleName, cssText) {
  var value = "", index;
  if( styleName && styleName != "" ) {
    if( ( index = cssText.indexOf(styleName) ) != -1 ) {
      value = cssText.substring( cssText.indexOf(":",index) + 1, cssText.indexOf(";",index) );
    }
  }
  return value;
}

/**
* Get Css degree
* 
* @param String orientation
*
* @return Object
*/
utils.getCssRotation = function(orientation) {
  if( !utils.getCssRotation.orientations ) {
    utils.getCssRotation.orientations = {
      'top-left': "0",
      'right-top': ($.browser.msie ? "1" : "90"),
      'bottom-right': ($.browser.msie ? "2" : "180"),
      'left-bottom': ($.browser.msie ? "3" : "270")
    };
  }
  if( !orientation ) orientation = "top-left";
  return utils.getCssRotation.orientations[orientation];
}

/**
* Get rotation style
* 
* @param Integer orientation
*
* @return String
*/
utils.getRotationStyle = function(orientation) {
  var rotateStyle = "";
  if( $.browser.msie ) {
    rotateStyle = "filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=" + utils.getCssRotation(orientation) + ");";
  } else if( $.browser.mozilla ) {
    rotateStyle = "-moz-transform:rotate(" + utils.getCssRotation(orientation) + "deg);";
  } else {
    rotateStyle = "-webkit-transform:rotate(" + utils.getCssRotation(orientation) + "deg);"
      + "transform:rotate(" + utils.getCssRotation(orientation) + "deg);";
  }
  return rotateStyle;
}

/**
* Get string from position
*
* @param String text
* @param Integer index
*
* @return Array
*/
utils.getStrAt = function(text, index) {
  if( $.browser.msie && $.browser.version == "7.0" ) {
   return text.split("")[index];
  } else {
    return text[index];
  }
}

/**
* Sort IXMLDOMDocument in asc and desc order by its query
*
* @param IXMLDOMDocument xmlDoc
* @param String query
* @param String sortByAttr
* @param String order
*
* @return IXMLDOMDocument
*/
utils.sortXML = function(xmlDoc , query,  sortByAttr, order) {

  var aryFind = new Array();
  sortByAttr = sortByAttr;
  xmlDoc = xmlDoc;
  query = query;
  order = order;

  if( order == "asc" ) {

    function compareAttr(a, b) {
      var sortA = a.sortByAttr.toLowerCase();
      var sortB = b.sortByAttr.toLowerCase();

      if( sortA < sortB ) return -1;
      if( sortA > sortB ) return 1;
      return 0;
    }

    $(xmlDoc.documentElement).find(query).each( function(value, fsFolder) {
      aryFind.push( { xmlNode : fsFolder.cloneNode(true), sortByAttr : $(fsFolder).attr('name') } );
    });

    if( aryFind && aryFind.length > 0 ) {
      aryFind.sort(compareAttr);

      var childItems =  $(xmlDoc.documentElement).find(query);
      for( var i = 0, len = childItems.length; i < len; i++ ) {
        var oldNode = childItems[i];
        var newNode = aryFind[i].xmlNode;
        oldNode.parentNode.replaceChild(newNode, oldNode);
      }
    }
  } else if ( order == "desc" ) {

    function compareAttribute(a, b) {
      var sortAA = a.sortByAttr.toLowerCase();
      var sortBB = b.sortByAttr.toLowerCase();

      if( sortAA < sortBB ) return 1;
      if( sortAA > sortBB ) return -1;
      return 0;
    }

    $(xmlDoc.documentElement).find(query).each( function(value, fsFolder) {
      aryFind.push( { xmlNode : fsFolder.cloneNode(true), sortByAttr : $(fsFolder).attr('name') } );
    });

    if( aryFind && aryFind.length > 0 ) {
      aryFind.sort(compareAttribute);

      var childItems =  $(xmlDoc.documentElement).find(query);
      for( var i = 0, len = childItems.length; i < len; i++ ) {
        var oldNode = childItems[i];
        var newNode = aryFind[i].xmlNode;
        oldNode.parentNode.replaceChild(newNode, oldNode);
      }
    }
  }

  return xmlDoc
}
/**
* remove files
*
* @param IXMLDOMDocument xmlDoc
* 
* @return IXMLDOMDocument
*/
utils.removeFiles = function(xmlDoc) {
  if( !xmlDoc ) return xmlDoc;

  var removeFile = { "settings.xml" : true };

  $(xmlDoc.documentElement).find(( $.browser.webkit || $.browser.opera ? 'entry' : 'atom\\:entry')).each( function(value, entry) {
    if( removeFile[$(this).find(( $.browser.webkit || $.browser.opera ? 'title' :'atom\\:title')).text()] ) {
      $(entry).remove();
    }
  });

  return xmlDoc;
}

/**
* obj containing attributes name
*
* @param Object obj
* @param IXMLDOMNode xmlNode
*
* @return Array
*/
utils.getChildTextAttrsByObj = function (obj, xmlNode) {
  if( !xmlNode || !obj ) return null;

  var aryChilds = [];
  var len = xmlNode.childNodes.length, childNode = null;
  for( var i = 0; i < len; i++ ) {
    childNode = xmlNode.childNodes[i];
    if( childNode.nodeType == 1 ) {
      var o = {};
      for( attrName in obj ) {
        o[attrName] = $(childNode).attr(attrName);
        if( !o[attrName] ) o[attrName] = null; // dont what 'undefined'
      }
      aryChilds.push(o);
    }
  }

  return aryChilds;
}

/**
* Gets the inner text from IXMLDOMNodes
*
* @param Object obj
* @param IXMLDOMNode xmlNode
* 
* @return Object
*/
utils.getChildTextNodesByObj = function(Obj, xmlNode) {
  var childNodes = utils.getChildNodesByObj(Obj, xmlNode);

  for( childName in Obj ) {
    if( childNodes[childName] ) {
      Obj[childName] = ( Obj[childName].toLowerCase() == "string" ? $(childNodes[childName]).text() : $(childNodes[childName]) );
    } else {
      Obj[childName] = null;
    }
  }
  return Obj;
}


/**
* Gets IXMLDOMNodes from IXMLDOMNode
*
* @param Object obj
* @param IXMLDOMNode xmlNode
*
* @return Object
*/
utils.getChildNodesByObj = function(obj, xmlNode) {

 var childNodes = {}, counter = 0;
  var i = 0, len = xmlNode.childNodes.length, childNode = null, childName = "";
  do {
    childNode = xmlNode.childNodes[i];
    childName = childNode.localName || childNode.baseName;
    if( childNode.nodeType == 1 && childName in obj ) {
      if( childNodes[childName] ) { // childNode already added, add a counter
        childNodes[childName + "_" + counter] = childNode;
      } else {
        childNodes[childName] = childNode;
      }
    }
  } while( ++i < len );

  return childNodes;
}

/**
* Compares Arrays
*
* @param Array aryA
* @param Array aryB
*
* @return Array ary
*  returns Array of boolean
*/
utils.compareArrays = function(aryA, aryB) {
  if( !aryA || !aryB ) return null;

  var aryBoolean = new Array();

  if( aryA && aryA.length > 0 ) {
    if( aryB && aryB.lenght > 0 ) {
      if( aryB.length == aryA.length ) {
        for( var i = 0, len = aryA.length; i < len; i++ ) {
          if( aryA[i] == aryB[i] ) {
            aryBoolean.push(true);
          } else {
            aryBoolean.push(false);
          }
        }
      }
    }
  }
}

/**
* Gets contained controls in a Form
*
* @param HTMLDOMNode form
*
* @return Object
*  returns Object of Form elems (input, textarea, radio, checkbox..)
*/
utils.getFromElems = function(form) {
  var objFormElems = null, formElem = null;
  for( var i = 0, len = form.elements.length; i < len; i++) {
    formElem = form.elements[i];
    if( !objFormElems ) objFormElems = new Object();
    objFormElems[formElem.id] = formElem;
  }
  return objFormElems;
}

utils.stopEvent = function(evt) {
  if( !evt ) return false;
  var agent = $.browser;
  if( agent.msie ) {
	  evt.cancelBubble = true;
  } else {
	  evt.stopPropagation();
  }
  return false;
}

/**
* Vertical Scroll Down HTMLDOMNode
*
* @param HTMLDOMNode elem
* @param Integer from
* @param Integer to
* @param Integer delays
* @param Boolean fadeIn
* @param Function callBack
*/
utils.smoothVerticalExpandElem = function(elem, from, to, delays, fadeIn, callBack) {
  if( !elem ) return;
  if( isNaN(from) || isNaN(to) ) return;

  if( isNaN(delays) ) delays = 10;

  if( elem.style.position != "relative" ) elem.style.position = "relative";

  var next = 0, y = 0;
  var speed = 10;

  var delay = setInterval( function() {
    if( fadeIn ) {
      $(elem).css({'opacity' : ( ( 1 / ( to - from ) ) * next ) });
    }

    if( next < ( to - from ) ) {
      elem.style.height = from + parseInt(y, 10) + "px";
      y = ( to - from ) * Math.sin( ( ( Math.PI / 2 ) / ( to - from ) ) * next );
      next += speed;
    } else {
      if( fadeIn ) $(elem).css({'opacity' : 1});
      clearInterval(delay)
      delay = null;
      if( callBack ) callBack();
      return;
    }
  },delays);
}

/**
* Vertical Scroll up HTMLDOMNode
*
* @param HTMLNode elem
* @param Integer from
* @param Integer to
* @param Integer delays
* @param Boolean fadeout
* @param Function callBack
*/
utils.smoothVerticalCollapseElem = function(elem, from, to, delays, fadeOut, callBack) {
  if( !elem ) return;
  if( isNaN(from) || isNaN(to) ) return;

  if( isNaN(delays) ) delays = 10;

  if( elem.style.position != "relative" ) elem.style.position = "relative";

  var next = 0, y = 0;
  var speed = 10;

  var delay = setInterval( function() {
    if( fadeOut ) {
      $(elem).css({'opacity' : ( 1 - ( ( 1 / ( from - to ) ) * next ) ) });
    }
    if( next < ( from - to ) ) {
      elem.style.height = from - parseInt(y, 10) + "px";
      y = ( from - to ) * Math.sin( ( ( Math.PI / 2 ) / ( from - to ) ) * next );
      next += speed;
    } else {
      if( fadeOut ) $(elem).css({'opacity' : 0});
      clearInterval(delay);
      delay = null;
      if( callBack ) callBack();
      return;
    }
  }, delays);
}

/**
* FadeIn HTMLDOMNode
*
* @param HTMLNode elem
* @param Integer delays
* @param Function callBack
*/
utils.fadeIn = function(elem, delays, callBack) {
  if( !elem ) return;

  if( isNaN(delays) ) delays = 10;
  var next = 0;

  var delay = setInterval( function() {
    if( next < delays ) {
      $(elem).css({'opacity' : ( ( 1 / delays ) * next ) });
      next++;
    } else {
      $(elem).css({'opacity' : 1});
      clearInterval(delay);
      delay = null;
      if( callBack ) callBack();
      return;
    }
  }, delays);
}

/**
* fadeOut HTMLDOMNode
*
* @param HTMLDOMNode elem
* @param Integer  delays
* @param Function callBack
*/
utils.fadeOut = function(elem, delays, callBack) {
  if( !elem ) return;

  if( isNaN(delays) ) delays = 10;
  var next = 0;

  var delay = setInterval( function() {
    if( next < delays ) {
      $(elem).css({'opacity' : ( 1 - ( ( 1 / delays ) * next ) ) });
      next++;
    } else {
      $(elem).css({'opacity' : 0});
      clearInterval(delay);
      delay = null;
      if( callBack ) callBack();
      return;
    }
  }, delays);
}
