//----------------------------------------------------
// show_help
//----------------------------------------------------
function show_help()
{
  var vwidth = Math.round(0.90*screen.width);
  var vheight = Math.round(0.75*screen.height);

  var vtop = 10;
  var vleft = 40;

  properties = "status=yes,resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;

  var ctx = "";
  if(typeof get_help_context == "function")
    ctx = "?context=" + get_help_context();
      
  var wnd = window.open("help.php" + ctx, "", properties);
  wnd.focus();
}
function show_wwg_help()
{
  var vwidth = Math.round(0.90*screen.width);
  var vheight = Math.round(0.75*screen.height);

  var vtop = 10;
  var vleft = 40;

  properties = "status=yes,resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;
      
  var wnd = window.open("help.php?context=wysiwyg_editor", "", properties);
  wnd.focus();
}
//----------------------------------------------------
// show_preview
//----------------------------------------------------
function show_preview()
{
  var vwidth = Math.round(0.9*screen.width);
  var vheight = Math.round(0.7*screen.height);

  var vtop = 30;
  var vleft = 30;

  properties = "status=yes,resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,location=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;

  var wnd = window.open("../", "sitepreview", properties);
  wnd.focus();
}
//----------------------------------------------------
// show_about
//----------------------------------------------------
function show_about()
{
  vwidth = 850;
  vheight = 550;

  vtop = 80;
  vleft = 100;

  properties = "status=yes,resizable=yes,scrollbars=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;

  var wnd = window.open("about.php", "about", properties);
  wnd.focus();
} // show_editor
//----------------------------------------------------
// show_about
//----------------------------------------------------
function show_file_manager(params)
{
  vwidth = "700";
  vheight = Math.round(0.75*screen.height);

  vtop = Math.round(0.4*(screen.height - vheight)/2);
  vleft = Math.round(1.4*(screen.width - vwidth)/2);

  properties = "status=yes,resizable=yes,scrollbars=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;

  var wnd = window.open("file_manager.php" + params, "file_manager", properties);
  wnd.focus();
} // show_file_manager

var second_window = null;
function show_editor(url, win_name)
{
  var vwidth = Math.round(0.93*screen.width);
  var vheight = Math.round(0.75*screen.height);

  var vtop = Math.round(0.4*(screen.height - vheight)/2);
  var vleft = Math.round(1.4*(screen.width - vwidth)/2);

  var properties = "status=yes,resizable=yes,scrollbars=yes" +
      ",width="+vwidth+
      ",height="+vheight+
      ",top="+vtop+
      ",left="+vleft;

  if(second_window && !second_window.closed)
  {
    alert(msg_second_window_open);
    second_window.focus();
    return;
  }
  
  second_window = window.open(url, "", properties);
  if(second_window) second_window.focus();
} // show_editor

//----------------------------------------------------
// searchNode
//----------------------------------------------------
function getCurrentStyle(obj, cAttribute)
{
	//if IE or Opera
	if (obj.currentStyle)
	{
		var curVal = eval('obj.currentStyle.'+cAttribute)
	} else
	{
		//if Mozilla/FF
		var curVal = eval('document.defaultView.getComputedStyle(obj, null).'+cAttribute)
	}
	//alert('style attribute '+cAttribute+' = ' + curVal)
	return curVal;
}
//----------------------------------------------------
// searchNode
//----------------------------------------------------
function close_window()
{
  if(data_was_modified && !confirm_data_lost()) return;

  window.close();
}
//----------------------------------------------------
// searchNode
//----------------------------------------------------
function searchNode(oRoot, strNodeName)
{
	var oNode = oRoot.firstChild;
	if (!oNode) 
		return false;
	if (oNode.nodeName == strNodeName)
	{
		// founded
		return oNode;
	} else
	{
		// not found, search again
		return searchNode(oNode, strNodeName);
	}
}
//----------------------------------------------------
// get_inner_dimensions
//----------------------------------------------------
function get_inner_dimensions()
{
  var x,y;
  if (self.innerHeight) // all except Explorer
  {
  	x = self.innerWidth;
  	y = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
  	// Explorer 6 Strict Mode
  {
  	x = document.documentElement.clientWidth;
  	y = document.documentElement.clientHeight;
  }
  else if (document.body) // other Explorers
  {
  	x = document.body.clientWidth;
  	y = document.body.clientHeight;
  }
  
  return { 'x' : x, 'y' : y };
}
//----------------------------------------------------
// showHideSection
//----------------------------------------------------
function showHideSection(id)
{
  var elm = document.getElementById(id);
  if(elm == null) return;

  if(elm.currentStyle.display != "none") elm.style.display = "none";
  else                                   elm.style.display = "block";
}
//----------------------------------------------------
// resores default selection of the list
//----------------------------------------------------
function restoreDefaultSelection(list)
{
  list.options.selectedIndex = 0;

  for(var i = 0; i < list.length; i++)
  {
    list.options[i].selected = list.options[i].defaultSelected;
  }
}

// selects list item by its value
function selectValue(list, value)
{
  list.options.selectedIndex = 0;

  for(var i = 0; i < list.length; i++)
  {
    list.options[i].selected = (list.options[i].value == value);
  }
}

function selectedText(list)
{
  for(var i = 0; i < list.length; i++)
  {
    if(list.options[i].selected) return list.options[i].text;
  }
  
  return "";
}
//----------------------------------------------------
// moves selected items from one list to another
//----------------------------------------------------
function moveSelectedItems(source_list, target_list)
{
  for(var i = 0; i < source_list.length; i++)
  {
    if(source_list.options[i].selected)
    {
      var option = new Option(source_list.options[i].text,
                              source_list.options[i].value,
                              false, true
                             );
      target_list.options[target_list.length] = option;
    }
  }

  for(var i = source_list.length - 1; i >= 0 ; i--)
  {
    if(source_list.options[i].selected)
    {
      source_list.options[i] = null;
    }
  }
}

// selects all items of the list
function selectAll(list)
{
  for(var i = 0; i < list.length; i++)
  {
    list.options[i].selected = true;
  }
}

function unselectAll(list)
{
  for(var i = 0; i < list.length; i++)
  {
    list.options[i].selected = false;
  }
}

function clear_form_fields(form)
{
  for(var i = 0; i < form.elements.length; i++)
  {
    var element = form.elements[i];
    
    if((element.type == "text") || (element.type == "hidden") ||
       (element.type == "password") || (element.type == "textarea")
      )
    {
      element.value = "";
    }
    else if((element.type == "radio") || (element.type == "checkbox"))
    {
      element.checked = false;
    }
    else if(element.type == "select-one") 
    {
      element.selectedIndex = 0;
    }
    else if(element.type == "select-multiple")
    {
      element.selectedIndex = -1;
    }
  }
}

function invert_pair_checkbox(src_chbk, trg_id)
{
  var elm = document.getElementById(trg_id);

  if(!src_chbk.checked || !elm || !elm.checked) return;

  elm.checked = false;
}

//----------------------------------------------------
// checks whether selection was changed
//----------------------------------------------------
function selectionChanged(list)
{
  for(var i = 0; i < list.length; i++)
  {
    if(list.options[i].selected != list.options[i].defaultSelected) return true;
  }

  return false;
}
//----------------------------------------------------
// set text message in dictionary
//----------------------------------------------------
var msg_text_not_found = 'no text for message key "{%s}"';
var msg_cant_redefine_msg = 'Can\'t redefine message for key "{%s}"';
function set_js_text(msgKey, msgValue)
{
	if (!msgKey)
		return false;
	
	// create singleton object
	if (!top._msgObj)
	{
		top._msgObj = {};
	}
	
	// if message with this key already exists and will be rewrited
	if(top._msgObj[msgKey] && top._msgObj[msgKey] != msgValue)
	{
		// do not rewrite messages
		alert(msg_cant_redefine_msg.replace(/{%s}/, msgKey));
		return false;
	} else
	{
		top._msgObj[msgKey] = msgValue;
	}
}
//----------------------------------------------------
// get text message from dictionary
//----------------------------------------------------
function get_js_text(msgKey)
{
	if (!top._msgObj || !top._msgObj[msgKey])
	{
		return msg_text_not_found.replace(/{%s}/, msgKey);
	}
	return top._msgObj[msgKey];
}
//----------------------------------------------------
// checks element for modifications
//----------------------------------------------------
var data_was_modified = false;
function check_modified(element)
{
  if(data_was_modified) return;

  if(element.modified)
  {
    data_was_modified = true;
    return;
  }

  if((element.type == "text") || (element.type == "hidden") ||
     (element.type == "password") || (element.type == "textarea")
    )
  {
    data_was_modified = (element.value != element.defaultValue);
  }
  else if((element.type == "radio") || (element.type == "checkbox"))
  {
    data_was_modified = (element.checked != element.defaultChecked);
  }
  else if((element.type == "select-one") || (element.type == "select-multiple"))
  {
    data_was_modified = selectionChanged(element);
  }
} // function check_modified(element)

function confirm_data_lost()
{
  if(!data_was_modified) return true;
  
  return confirm(get_js_text('MsgCancelConfirm'));
}

function go_to_url(url)
{
  if(!confirm_data_lost()) return false;
  document.location.href = url;
}

//----------------------------------------------------
// date utils, number utils
//----------------------------------------------------

// remainder
function utmod(num, dev)
{
  var sign = (num < 0) ? -1 : 1;

  return sign*((sign*num) % dev);
}

// integer part
function utint(num, dev)
{
  return (num - utmod(num, dev)) / dev;
}

function isLeapYear(year)
{
  return (((utmod(year, 4)   == 0) &&
           (utmod(year, 100) != 0)
          ) ||
          (utmod(year, 400)  == 0)
         );
}

function getDaysInMonth(month, year)
{
  if(month == 1) return 31;
  if(month == 2) return (isLeapYear(year)) ? 29 : 28;

  return (2*(month + 1) + utint(3*((month + 1) + 1), 5) - 5) -
         (2*(month)     + utint(3*((month)     + 1), 5) - 5) +
         28;
}

function validateDate(day, month, year)
{
  if(isNaN(day) || isNaN(month) || isNaN(year)) return false;
  if(month < 1 || month > 12)
  {
    return false;
  }

  if(day < 1 || day > getDaysInMonth(1*month, 1*year))
  {
    return false;
  }

  return true;
}

function insert(str, ins, pos)
{
  part1 = str.substring(0, pos);

  part2 = str.substring(pos, str.length);

  return part1 + ins + part2;
}

function float_to_string(val, precision)
{
  if(isNaN(val)) return "";

  var sign = "";

  val = parseFloat(val);

  if(val < 0.0)
  {
    val = -val;
    sign = "-";
  }

  var startPos = 0;
  if(val < 1.0)
  {
    val += 10.0;
    startPos = 1;
  }

  val = Math.round(val * Math.pow(10, precision));

  var str = String(val);

  return sign + str.substr(startPos, str.length - precision - startPos) + "." + str.substr(str.length - precision, precision);
}

function int_to_string(val)
{
  if(isNaN(val)) return "";

  return new String(val);
}

function time_to_string(time, format)
{
  if(!time) return "";

  var timestr = format;
  var aux;

  aux = new String(time.getDate());
  if(aux.length == 1) aux = "0" + "" + aux;
  timestr = timestr.replace(/d/, aux);

  aux = new String(time.getMonth() + 1);
  if(aux.length == 1) aux = "0" + "" + aux;
  timestr = timestr.replace(/m/, aux);

  timestr = timestr.replace(/Y/, time.getFullYear());

  aux = new String(time.getHours());
  if(aux.length == 1) aux = "0" + "" + aux;
  timestr = timestr.replace(/H/, aux);

  aux = new String(time.getMinutes());
  if(aux.length == 1) aux = "0" + "" + aux;
  timestr = timestr.replace(/i/, aux);

  aux = new String(time.getSeconds());
  if(aux.length == 1) aux = "0" + "" + aux;
  timestr = timestr.replace(/s/, aux);

  return timestr;
}

function string_to_time(str, format)
{
  var pattern = format;

  pattern = pattern.replace(/\./g, "\\.");
  pattern = pattern.replace(/\//g, "\\/");

  pattern = pattern.replace(/d/, "([0-9]{1,2})");
  pattern = pattern.replace(/m/, "([0-9]{1,2})");
  pattern = pattern.replace(/Y/, "([0-9]{4})");
  pattern = pattern.replace(/H/, "([0-9]{1,2})");
  pattern = pattern.replace(/i/, "([0-9]{1,2})");
  pattern = pattern.replace(/s/, "([0-9]{1,2})");

  eval("var re = /" + pattern + "/;");
  var result = re.exec(str);

  if(!result) return null;

  var units = new Array();
  units[0] = RegExp.$1;
  units[1] = RegExp.$2;
  units[2] = RegExp.$3;
  units[3] = RegExp.$4;
  units[4] = RegExp.$5;
  units[5] = RegExp.$6;

  var order = format.replace(/[^YmdHis]/g, "");

  var i_year = order.indexOf("Y");
  var i_month = order.indexOf("m");
  var i_day = order.indexOf("d");
  var i_hour = order.indexOf("H");
  var i_minute = order.indexOf("i");
  var i_second = order.indexOf("s");

  var date_ok = false;
  var time_ok = false;

  if(i_year != -1 && i_month != -1 && i_day != -1) date_ok = true;
  if(i_hour != -1 && i_minute != -1) time_ok = true;

  if(!date_ok && !time_ok) return null;

/*
    alert(units[i_day] + "." + units[i_month] + "." + units[i_year] + " " +
          units[i_hour] + ":" + units[i_minute] + ":" + units[i_second]
         );
*/

  var dt = new Date();

  if(date_ok)
  {
    if(!validateDate(units[i_day], units[i_month], units[i_year])) return null;

    dt.setFullYear(units[i_year]);
    dt.setMonth(units[i_month] - 1);
    dt.setDate(units[i_day]);
  }

  if(time_ok)
  {
    if(isNaN(units[i_hour]) || units[i_hour] < 0 || units[i_hour] > 23) return null;
    if(isNaN(units[i_minute]) || units[i_minute] < 0 || units[i_minute] > 59) return null;

    dt.setHours(units[i_hour]);
    dt.setMinutes(units[i_minute]);
  }
  else
  {
    dt.setHours(0);
    dt.setMinutes(0);
  }

  if(i_second != -1)
  {
    if(isNaN(units[i_second]) || units[i_second] < 0 || units[i_second] > 59) return null;

    dt.setSeconds(units[i_second]);
  }
  else
  {
    dt.setSeconds(0);
  }

  return dt;
}

function preprocess_int(elm)
{
  if(elm.value == "")
  {
    elm.defaultValue = elm.value;
    return false;
  }

  if(isNaN(elm.value))
  {
    elm.value = elm.defaultValue;
    return false;
  }

  var tmp = parseInt(1*elm.value);
  elm.value = tmp;
  elm.modified = (elm.defaultValue != elm.value);
  elm.defaultValue = elm.value;

  return true;
}

function preprocess_float(elm)
{
  if(elm.value == "")
  {
    elm.defaultValue = elm.value;
    return false;
  }

  if(isNaN(elm.value))
  {
    elm.value = elm.defaultValue;
    return false;
  }

  var tmp = parseFloat(elm.value);
  elm.value = float_to_string(tmp, 2);

  elm.modified = (elm.defaultValue != elm.value);
  elm.defaultValue = elm.value;

  return true;
}

function preprocess_number(elm)
{
  if(elm.value == "")
  {
    elm.defaultValue = elm.value;
    return false;
  }

  if(isNaN(elm.value))
  {
    elm.value = elm.defaultValue;
    return false;
  }

  var tmp = parseFloat(elm.value);
  elm.value = String(tmp);

  elm.modified = (elm.defaultValue != elm.value);
  elm.defaultValue = elm.value;

  return true;
}

function preprocess_time(elm, format)
{
  if(elm.value == "")
  {
    elm.defaultValue = elm.value;
    return false;
  }

  var tmp = string_to_time(elm.value, format);
  if(tmp == null)
  {
    elm.value = elm.defaultValue;
    return false;
  }

  elm.value = time_to_string(tmp, format);
  elm.modified = (elm.defaultValue != elm.value);
  elm.defaultValue = elm.value;

  return true;
}

function extractFilename(strPath)
{
	var iLastSlashPos = strPath.lastIndexOf('\\');
	
  if (iLastSlashPos != -1)
	{
		strPath = strPath.slice(iLastSlashPos+1)
	} 
  else
	{
		var iLastSlashPos = strPath.lastIndexOf('/');
		if (iLastSlashPos != -1)
		{
			strPath = strPath.slice(iLastSlashPos+1)
		}
	}
  
	return strPath;
}

function toggleThumbnail(ckbx, ownerId)
{
	
	var checked = $(ckbx).attr('checked');
	if (checked)
	{
		$(':checkbox:checked[value!='+ ckbx.value+']', '#'+ownerId).each(function(i, o){
			$(this).attr('checked', false);
			var thumbnail = $(this).parents('.thumbnail-std-table').get(0);
			unhighlightThumbnail(thumbnail);
		});

		var thumbnail = $(ckbx).parents('.thumbnail-std-table').get(0);
		highlightThumbnail(thumbnail);
		return true;
	} else
	{
		var thumbnail = $(ckbx).parents('.thumbnail-std-table').get(0);
		unhighlightThumbnail(thumbnail);
		return true;
	}
	
}

function highlightThumbnail(thumbnail)
{
	$(thumbnail).addClass('selected');
}

function unhighlightThumbnail(thumbnail)
{
	$(thumbnail).removeClass('selected');
}

function showBlock(id){
	$('#'+id).css('display', 'block');
}

function hideBlock(id){
	$('#'+id).css('display', 'none');
}

// this function must be called when You put a new content (response) from ajax handler on server side.
function ajaxnoaccess(){
	location.reload();
}

function getAssocInfo(arAssoc)
{
	var buf = '';
	for (var i in arAssoc)
		buf+= i+ ':'+ arAssoc[i]+ '\n';
	
	return buf;
}

function getArInfo(ar)
{
	if (!ar)
		return '';
	var buf = '';
	
	for (var i=0, len = ar.length; i<len; i++)
		buf+= i+ ':'+ ar[i]+ '\n';
	
	return buf;
}

function getWaiter()
{
	var $waiter = $('#waiter_elmnt');
	if ($waiter.length==0)
	{
		$waiter = $('<div />').attr('id', 'waiter_elmnt').prependTo('body');
	}
	return $waiter;
}

function showWaiter(opts)
{
	var $waiter = getWaiter();
	$waiter.css('display', 'block');
	var msg = opts.msg || '';
	$waiter.text(msg);
}

function hideWaiter(opts)
{
	var $waiter = getWaiter();
	$waiter.css('display', 'none');
}
