   
/***************************************************************************
 *                              utils.js
 *                              ---------
 *   begin                : Ignatov V. Oleg, Apr 19, 2006
 *   author               : Ignatov V. Oleg (o.ignatov@westpower.ru)
 *   author               : Shelenkov V. Evgeniy (e.shelenkov@westpower.ru)
 *   copyright            : (C) 2006-2008 West Power Development Studio 
 *   mail                 : support@westpower.ru
 *   url                  : www.westpower.ru
 *   license              : commerce
 *
 *   $Id: utils.inc.js,v 1.30 2007/08/10 14:53:31 O-Ignatov\E.shelenkov Exp $
 *
 ***************************************************************************/


/** КЛАСС дополнительных ф-ции и перемсенных **/

utils = function utils()
{
   
};

utils.client_pc  = navigator.userAgent.toLowerCase(); // Get client info
utils.client_ver = parseInt(navigator.appVersion); // Get browser version

utils.is_ie  = ((utils.client_pc.indexOf("msie") != -1)  && (utils.client_pc.indexOf("opera") == -1));
utils.is_nav = ((utils.client_pc.indexOf('mozilla')!=-1) && (utils.client_pc.indexOf('opera')==-1) && (utils.client_pc.indexOf('compatible') == -1) && (utils.client_pc.indexOf('hotjava')==-1) && (utils.client_pc.indexOf('webtv')==-1) && (utils.client_pc.indexOf('spoofer')==-1));
utils.is_moz = 0;
utils.is_win = ((utils.client_pc.indexOf("win")!=-1) || (utils.client_pc.indexOf("16bit") != -1));
utils.is_mac =  (utils.client_pc.indexOf("mac")!=-1);
	   
utils.print_r = function(array)
{
   var text = '';
   for (var id in array){
       text = text+" ["+id+"] = "+array[id]+";\n";
   };
   alert(text);
};


utils.print_box = function (array)
{
   var text = '';
   for (var id in array){
       text = text+" ["+id+"] = "+array[id]+";\n";
   };
   document.write('<textarea style="width:100%; height:300px">'+text+'</textarea>');
};

utils.in_array_object = function (id, haystack) 
{
   for (var value in  haystack) {
      if (haystack[value].id == id) {
         return true;
      }
   }
   return false;
};

utils.in_array = function (id, haystack) 
{
   for (var i = 0; i < haystack.length; i++) {
      if (haystack[i] == id) {
         return true;
      }
   }
   return false;
};

utils.mozilla_wrap = function (textarea, open_tag, close_tag) {
   var select_length = textarea.textLength;
   var select_start  = textarea.selectionStart;
   var select_end    = textarea.selectionEnd;
   if (select_end == 1 || select_end == 2) {
      select_end = select_length;
   }
   var part_1 = (textarea.value).substring(0,select_start);
   var part_2 = (textarea.value).substring(select_start, select_end)
   var part_3 = (textarea.value).substring(select_end, select_length);
   textarea.value = part_1 + open_tag + part_2 + close_tag + part_3;
   return;
}

utils.str_replace = function (search, replace, subject)
{
   if (replace == subject) {
      return search;
   }
   
   var replace_location = search.indexOf(replace);
   var temp_string  = search;
   var left_string  = '';
   var right_string = '';
   while (replace_location != -1) {
      left_string = temp_string.substring(0, replace_location);
      right_string = temp_string.substring(replace_location + replace.length);
      temp_string = left_string + subject + right_string;
      replace_location = temp_string.indexOf(replace);
   }
   return temp_string;
};

utils.get_top_pos = function (inputObj)
{
   var returnValue = inputObj.offsetTop;
   while((inputObj = inputObj.offsetParent) != null){
      if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
   }
   return returnValue;
};

utils.get_left_pos = function (inputObj)
{
   var returnValue = inputObj.offsetLeft;
	while((inputObj = inputObj.offsetParent) != null){
	   if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
	}
	return returnValue;
};

utils.get_array_size = function (array) {
   for (i = 0; i < array.length; i++) {
      if ((array[i] == "undefined") || (array[i] == "") || (array[i] == null)) {
         return i;
      }
   }
   return array.length;
}

utils.array_push = function (array, value) {
   array[utils.get_array_size(array)] = value;
}

utils.array_delete_last = function (array) {
   array_size = utils.get_array_size(array);
   retval = array[array_size - 1];
   delete array[array_size - 1];
   return retval;
}

utils.store_caret = function (textEl) {
   if (textEl.createTextRange) {
      textEl.caretPos = document.selection.createRange().duplicate();
   }
}

utils.open_popup_window = function (url)
{
	window.open(url,'full_window','height='+screen.availHeight+',width='+screen.availWidth+',scrollbars=yes,status=no,menubar=no,location=no,directories=no,fullscreen=yes,resizable=yes');
}

utils.show_hide = function (elmt_id)
{ 
   var new_element_id = elmt_id + '_body';
    
   if (document.getElementById(elmt_id + '_body').style.display == "none") {
	 	document.getElementById(elmt_id + '_body').style.display = "block";
   } else {
	   document.getElementById(elmt_id + '_body').style.display = "none";
   }
}

utils.show = function (elmt_id)
{ 
   var new_element_id = elmt_id + '_body';
    
   if (utils.is_ie) {  
  	 	   document.getElementById(elmt_id + '_body').style.display = "block";
	} else {
		   document.getElementById(elmt_id + '_body').style.display = "block";
	}
}

utils.hide = function (elmt_id)
{ 
   var new_element_id = elmt_id + '_body';
    
   document.getElementById(elmt_id + '_body').style.display = "none";
}


//utils.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );

   /// detect Opera browser
//utils.is_opera = /opera/i.test(navigator.userAgent);

   /// detect KHTML-based browsers
//utils.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent); 

/** КЛАСС работы с событиями **/

wp_event = function wp_event()
{
   
};


wp_event.get_element = function(ev) 
{
  // ev || (ev = window.event);

	if (utils.is_ie) {
		return ev.srcElement;
	} else {
		return ev.currentTarget;
	}
};

wp_event.get_target_element = function(ev) 
{
   ev || (ev = window.event);
	if (utils.is_ie) {
		return ev.srcElement;
	} else {
		return ev.target;
	}
};

wp_event.prototype.add = function(el, evname, func) 
{
	if (el.attachEvent) { // IE
		el.attachEvent("on" + evname, func);
	} else if (el.addEventListener) { // Gecko / W3C
		el.addEventListener(evname, func, true);
	} else {
		el["on" + evname] = func;
	}
	
};

wp_event.prototype.send = function(el, evname)
{
   if (el.fireEvent) {
      var ev = document.createEventObject();
      el.fireEvent("on" + evname, ev);
   } else if (el.dispatchEvent) {
      var ev = new Event();
      ev.initEvent(evname, true, true);
      el.dispatchEvent(ev);      
   }
};

wp_event.prototype.remove = function(el, evname, func) 
{
	if (el.detachEvent) { // IE
		el.detachEvent("on" + evname, func);
	} else if (el.removeEventListener) { // Gecko / W3C
		el.removeEventListener(evname, func, true);
	} else {
		el["on" + evname] = null;
	}
};

wp_event.prototype.stop = function(ev) {
	ev || (ev = window.event);
	if (utils.is_ie) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
};


/** прочие ф-ции **/

function wp_open_show(element_id)
{
   var element = document.getElementById(element_id);
   element.style.display = element.style.display == 'none' ? 'block' : 'none';
}

wp_modal_window = function wp_modal_window()
{
};

// инициализация модального окна
wp_modal_window.open = function (width, height, title, content)
{
   if (!width)  {
      width = screen.width / 2;
   }
   if (!height){
      height = screen.height / 2;
   }   
   // расположение окна - если покрытие модального дива больше чем модальное окно (вместе со скролом и 5 процентным смещением вниз) то окно смещяем на 5 процетов иначе просто отдаем координаты скрола.
   var ypos_modal_window = document.body.scrollHeight > document.body.scrollTop + height + (screen.height / 100 * 5) ?  document.body.scrollTop + (screen.height / 100 * 5) : document.body.scrollTop;
   this.modal_window = document.getElementById('modal_window');
   this.modal_window.style.display = 'block';
   this.modal_window.style.width = '100%';
   this.modal_window_hide = document.getElementById('modal_window_hide');
   this.modal_window_hide.style.display = 'block';
   // модальный див - растягиваем его так что бы модальное окно в смешении сразу было над ним.
   this.modal_window.style.height = document.body.scrollHeight > ypos_modal_window + height ? document.body.scrollHeight : ypos_modal_window + height; 
   this.modal_window_content = document.getElementById('modal_window_content');
   this.modal_window_content.style.display = 'block';   
   this.modal_window_content.style.width = width;
   this.modal_window_content.style.height = height; 
   this.modal_window_content.style.top = ypos_modal_window; 
   // определяем центровку экрана
   this.modal_window_content.style.left = (width > screen.width ? 0 : ((screen.width / 2) - (width / 2))); 
   // заполняем заголовок и тело дива нужными компонентами
   this.modal_window_title_html = document.getElementById('modal_window_title_html');
   this.modal_window_title_html.innerHTML = (title || '');
   // вызыв внешней функции для получения данных окна
   if (content) {
      wp_modal_window.set_content(content);
   } else {   
      wp_modal_window.set_content(WP_MODAL_WINDOW_WAIT);
   }
   // инициируем дополнительно выключение модального окна по нажатию ESC
   document.documentElement.onkeypress = wp_modal_window.keypress;
};

wp_modal_window.set_content = function (content)
{
   this.modal_window_content_html = document.getElementById('modal_window_content_html');
   this.modal_window_content_html.innerHTML = (content ? content : this.modal_window_content_html.innerHTML);
   document.getElementById('modal_window').style.height = (document.body.scrollHeight > document.getElementById('modal_window_end').offsetTop+6 ? document.body.scrollHeight : document.getElementById('modal_window_end').offsetTop+6);
}

// отключение модального окна по нажатию ESC
wp_modal_window.keypress = function (e)
{    
   e || (e = window.event);
   this.modal_window = document.getElementById('modal_window');
   this.modal_window_content = document.getElementById('modal_window_content');
   this.modal_window_hide = document.getElementById('modal_window_hide');
 	if ((e.keyCode == 27 || (e.charCode && e.charCode == 27)) && ((this.modal_window.style.display == 'block') && (this.modal_window_content.style.display = 'block'))) {
      this.modal_window.style.display = 'none';
      this.modal_window_content.style.display = 'none';
      this.modal_window_hide.style.display = 'none';    
 	}
};
// отключение модального окна по вызову функции
wp_modal_window.close = function ()
{    
   this.modal_window = document.getElementById('modal_window');
   this.modal_window_content = document.getElementById('modal_window_content');
   this.modal_window_hide = document.getElementById('modal_window_hide');
   this.modal_window.style.display = 'none';
   this.modal_window_content.style.display = 'none';   
   this.modal_window_hide.style.display = 'none';   
};
