
/***************************************************************************
 *                              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.36 2008/06/10 14:52:36 N.Safronov 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.is_firefox = ((utils.client_pc.indexOf("firefox") != -1));
utils.is_safari  = ((utils.client_pc.indexOf("safari") != -1));
utils.is_opera   = ((utils.client_pc.indexOf("opera") != -1));
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)
{
	// функция работает правильно (в софари) - только при выравнивании valign=top
   var returnValue = inputObj.offsetTop;
   while((inputObj = inputObj.offsetParent) != null){
      if(inputObj.tagName!='HTML') returnValue += inputObj.offsetTop;
   }
   return returnValue;
};

utils.get_left_pos = function (inputObj)
{
	// функция работает правильно (в софари) - только при выравнивании align=left
   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(new_element_id) == "undefined") ||
       (document.getElementById(new_element_id) == "") ||
       (document.getElementById(new_element_id) == null)) {
         return ;
   }
   if (document.getElementById(elmt_id + '_body').style.display == "none") {
	   if (utils.is_ie) {
  	  	   document.getElementById(elmt_id + '_body').style.display = "block";
	   } else {
	    	document.getElementById(elmt_id + '_body').style.display = "table";
	   }
   } 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.mouse_position = function (event)
{
   event || (event = window.event);
   var x_pos = 0;
   var y_pos = 0;
   if (!document.attachEvent && document.addEventListener) {
      x_pos = event.clientX + window.scrollX;
      y_pos = event.clientY + window.scrollY;
   }

   if (document.attachEvent != null) {
      x_pos = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
      y_pos = window.event.clientY + (document.documentElement.scrollTop  ? document.documentElement.scrollTop  : document.body.scrollTop);
   }

   return {x_pos:x_pos, y_pos:y_pos};
}


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, mwindow, mwindow_hide, mwindow_content, mwindow_content_html, mwindow_end, mwindow_title_html)
{
   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(mwindow);
   this.modal_window.style.display = 'block';
   this.modal_window.style.width = '100%';
   this.modal_window_hide = document.getElementById(mwindow_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(mwindow_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(mwindow_title_html);
   this.modal_window_title_html.innerHTML = (title || '');
   // вызыв внешней функции для получения данных окна
   if (content) {
      wp_modal_window.set_content(content, mwindow_content_html, mwindow, mwindow_end);
   } else {
      wp_modal_window.set_content(WP_MODAL_WINDOW_WAIT, mwindow_content_html, mwindow, mwindow_end);
   }

};

wp_modal_window.set_content = function (content, mwindow_content_html, mwindow, mwindow_end)
{
   this.modal_window_content_html = document.getElementById(mwindow_content_html);
   this.modal_window_content_html.innerHTML = (content ? content : this.modal_window_content_html.innerHTML);
   document.getElementById(mwindow).style.height = (document.body.scrollHeight > document.getElementById(mwindow_end).offsetTop+6 ? document.body.scrollHeight : document.getElementById(mwindow_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_console_window = function wp_console_window()
{
};

// отключение модального окна по нажатию ESC
wp_console_window.keypress = function (e)
{
   e || (e = window.event);
   modal_window = document.getElementById('modal_window');
   modal_window_content = document.getElementById('console_window_content');
   modal_window_hide = document.getElementById('modal_window_hide');
 	if ((e.keyCode == 27 || (e.charCode && e.charCode == 27)) && ((modal_window.style.display == 'block') && (modal_window_content.style.display = 'block'))) {
      modal_window.style.display = 'none';
      modal_window_content.style.display = 'none';
      modal_window_hide.style.display = 'none';
 	}
};
// отключение модального окна по вызову функции
wp_modal_window.close = function (mwindow, modal_wcontent, mwindow_hide)
{
   this.modal_window = document.getElementById(mwindow);
   this.modal_window_content = document.getElementById(modal_wcontent);
   this.modal_window_hide = document.getElementById(mwindow_hide);
   this.modal_window.style.display = 'none';
   this.modal_window_content.style.display = 'none';
   this.modal_window_hide.style.display = 'none';
};
