﻿////////////////////////////////////////////////////////////////////////////////
//
// utils.js - various utilites and helper functions
//
////////////////////////////////////////////////////////////////////////////////

// string is used for base64 conversions
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

////////////////////////////////////////////////////////////////////////////////
// The method used to encode given string into base64 representation
////////////////////////////////////////////////////////////////////////////////
function base64_encode(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}


////////////////////////////////////////////////////////////////////////////////
// The method used to decode given base64 sequence
////////////////////////////////////////////////////////////////////////////////
function base64_decode(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

////////////////////////////////////////////////////////////////////////////////
// The method returns URL parameter value by given name
////////////////////////////////////////////////////////////////////////////////
function get_url_parameter( name ){

  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


var isUserAgentGeckoLinuxBased = function(){

	var user_agent = new String(navigator.userAgent);

	return user_agent.indexOf("Linux", 0) > 0 
		&& user_agent.indexOf("Gecko/20", 0) > 0;
}


////////////////////////////////////////////////////////////////////////////////
// The method returns localized string representation of given date
////////////////////////////////////////////////////////////////////////////////
function GetLocalDateString(date, month, year) {
	var date = new Date(year, month-1, date);
	return date.toLocaleDateString();
}


////////////////////////////////////////////////////////////////////////////////
// The method returns true if given string is null or empty
////////////////////////////////////////////////////////////////////////////////
var isNullOrEmpty = function(str){

	return null == str || 0 == str.length || "null" == str;
}


////////////////////////////////////////////////////////////////////////////////
// The method used to disable enter key behaviour in forms
////////////////////////////////////////////////////////////////////////////////
function disableEnterKey(e){

	var key;      
	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox

	return (key != 13);
}


////////////////////////////////////////////////////////////////////////////////
// The method is used to simulate non W3C property 'innerText' in Mozilla 
// based browsers. See http://forum.vingrad.ru/faq/topic-158203.html
////////////////////////////////////////////////////////////////////////////////
function innerText(node) {
	var ret = "";
	
	if (null == node || null == node.childNodes)
		return;
	
	for(var i=0; i<node.childNodes.length; i++) {
	
		switch(node.childNodes[i].nodeType) {
			// if element
			case 1:
				ret+=innerText(node.childNodes[i]);
				break;
			// if text node
			case 3:
				ret+=node.childNodes[i].nodeValue;
				break;
		}
	}
	return ret;
}


////////////////////////////////////////////////////////////////////////////////
// The method allows you to sort json array by any field
// http://stackoverflow.com/questions/979256/how-to-sort-a-json-array
////////////////////////////////////////////////////////////////////////////////
var json_array_sort_by = function(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}


////////////////////////////////////////////////////////////////////////////////
// The method used to check server reply for an errors and update view
// true returned if any errors detected and false otherwise
////////////////////////////////////////////////////////////////////////////////
var CheckOfbServerReply = function(response){

	// make sure server response is not null
	if (null == response || null == response.result){
		info_message_panel_update("Error: server returned null response.");
		return true;
	}
	
	// try to get error message.
	var error_message = false == isNullOrEmpty(response.result.ERROR) 
		? response.result.ERROR 
		: null == response.result[0] ? null : response.result[0].ERROR;
		
	// do not continue if there are not any error messages
	if (isNullOrEmpty(error_message))
		return false;
	
	// update info message panel
	info_message_panel_update(error_message);

	// reload page if session is expired
	if ("SESSION_EXPIRED" == error_message){
		location.reload(true);
	}
	
	return true;
}


var getFileExtension = function(file_name){

	var pos = file_name.lastIndexOf('.');
	if (pos > 0)
		return file_name.substring(pos + 1).toLowerCase();
	else
		return null;
}

var isDirectory = function(file_type){
	return ITEM_TYPE_DIRECTORY == file_type;
}

var isValidEmail = function(email){
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email);
}

var getValue = function(id_or_object){

	if (typeof id_or_object == "string")
		return document.getElementById(id_or_object).value;
		
	if (typeof id_or_object == "object")
		return id_or_object.value;
		
	throw "utils::getValue::invalid argument";
}

var setValue = function(id_or_object, value){

	if (typeof id_or_object == "string"){
		document.getElementById(id_or_object).value = value;
	}
		
	else if (typeof id_or_object == "object"){
		id_or_object.value = value;
	}
	
	else throw "utils::setValue::invalid argument";
}

var setInnerHTML = function(id_or_object, value){

	if (typeof id_or_object == "string")
		document.getElementById(id_or_object).innerHTML = value;
		
	else if (typeof id_or_object == "object")
		id_or_object.innerHTML = value;
		
	else
		throw "utils::setInnerHTML::invalid argument";
}

var getInnerHTML = function(id_or_object, value){

	if (typeof id_or_object == "string")
		return document.getElementById(id_or_object).innerHTML;
		
	else if (typeof id_or_object == "object")
		return id_or_object.innerHTML;

	throw "utils::setInnerHTML::invalid argument";
}


var setClass = function(id_or_object, style){

	if (typeof id_or_object == "string")
		return document.getElementById(id_or_object).setAttribute("class", style);
		
	if (typeof id_or_object == "object")
		return id_or_object.setAttribute("class", style);
		
	throw "utils::setClass::invalid argument";
}

var getClass = function(id_or_object, style){

	if (typeof id_or_object == "string")
		return document.getElementById(id_or_object).getAttribute("class");
		
	if (typeof id_or_object == "object")
		return id_or_object.getAttribute("class")
		
	throw "utils::getClass::invalid argument";
}


var appendClass = function(id_or_object, class_to_append){
	
	var new_style = getClass(id_or_object) + " " + class_to_append;
	setClass(id_or_object, new_style);
}

var removeClass = function(id_or_object, class_to_remove){
	
	var new_style = getClass(id_or_object).replace(class_to_remove, "");
	setClass(id_or_object, new_style);
}