///////////////////
// AWD FUNCTIONS //
///////////////////

$(document).ready(function()
{
	prepare_level_select();
});

function trim(string)
{
	return string.replace(/\s/g, "");
}

function hide_window(elem_id)
{
	$("#" + elem_id).hide();
}


function prepare_level_select()
{
	$("select[tag='level_select']").each(function()
	{
		var id = $(this).attr('id');
		id = id + '_full';
		
		var form = $(this).clone();
		$(this).attr('tag1', 'level_select');
		$(this).removeAttr('tag');

		$(form).attr('id', id).hide().removeAttr('tag').appendTo('body');
		
		if ($(this).is(':visible'))
		{
			if ($(this).find('option').size() < 3)
				$(this).find("option[id*='option_all_']").remove();
			else
				$(this).find("option[id*='option_none_']").remove();
		}
	});
	
	$("select[tag1='level_select']").change();
}

function run(execute) {
  execute();
}

function select_level_run(elem)
{
	var str = $(elem).find('option:selected').attr('strOnCilick');

	if (str)
		eval(str);
}

function im(obj, url)
 {

  ob=document.getElementById(obj);
  ob.src=url;
 }


function checkDel()
 {
    var is_confirmed = confirm('Delete?');
    return is_confirmed;
    if (is_confirmed) 
     {
      link.href = 'this';
     }
 }
 
 function checkAction(text)
 {
    return confirm(text);
 }

function change_location(url)
 {
  window.location=url;
 }


function change_color(id,color)
 {
  id.style.backgroundColor = color;
 }
 

function choose_level(name, children, level)
{
  var sel_elem = $('#select_'+name+'_level_'+level).get(0);
  var sel_elem_parent = $(sel_elem).parent();
  
  $(sel_elem).remove();
  var sel_elem = $('#select_'+name+'_level_'+level+'_full').clone();

  option_all_click(name, level+1);
  var count = 0;
  
  $(sel_elem).find('option').each(function()
  {
    count++;
    if ($(this).attr('id') == '')
	{
		if ($.inArray($(this).val(), children) == -1)
		{
			$(this).remove();
			count--;
		}
	}
  });
  
  if (count < 3)
	$(sel_elem).find('option#option_all_'+name+'_level_'+level).remove();
  else
	$(sel_elem).find('option#option_none_'+name+'_level_'+level).remove();
	
  
  $(sel_elem).attr('id', 'select_'+name+'_level_'+level).show();
  $(sel_elem_parent).append(sel_elem);
  
  if($.browser.msie)
	$(sel_elem_parent).parent().show();
  else
    $(sel_elem_parent).parent().css('display', 'inherit');
}


function option_all_click(name, level)
{
  var select_elem;
  while (select_elem = document.getElementById('select_'+name+'_level_'+level))
  {
    $(select_elem).html($('#select_'+name+'_level_'+level).html());
    document.getElementById('option_all_'+name+'_level_'+level).selected = true;
    select_elem.parentNode.parentNode.style.display = "none"; //tr_elem
	level++;
  }
}


function show_level (name, selected)
{
 for (i=0;i<selected.length;i++)
  {
    var select_elem = document.getElementById('select_'+name+'_level_'+ i);
    for (j=0;j<select_elem.childNodes.length;j++)
      if (select_elem.childNodes[j].value == selected[i])
	    select_elem.childNodes[j].click();
  }
}

function check_careprovider()
{
  var select_elem = document.getElementById('select_location_level_1');
  var value = select_elem.options[select_elem.selectedIndex].value;
  
  if (value)
    getAjax('./ajax_careprovider_count.php?id='+value,'check_content');
  else
    alert ('Please choose your City!');
}


/////////////////////
// OTHER FUNCTIONS //
/////////////////////

// Очистка полей
function empty(variable, val)
{
	var obj = document.getElementById(variable);

	if (obj.value == val)
		obj.value = '';
}

// Фильтр длины
function filter(max_length, textarea, to_simbols)
{
	var obj_textarea = document.getElementById(textarea);
	var obj_to_simbols = document.getElementById(to_simbols);

	var message = obj_textarea.value;
	var message_length=message.length;
	var diff=max_length-message_length;
	
	if(diff<0) 
		diff=0;

	obj_to_simbols.value=diff;

	if(message_length > max_length) 
	{
		obj_textarea.value = message.substring(0, max_length);
	}
}


function onlyNumbers(id)
{
	var num = $('#'+id).val();
	var length = num.length;
	var regex_class = new RegExp("^[0-9]*$");
	
	if(!regex_class.test(num)) 
	{
		length -= 1;
		$('#'+id).val(num.substring(0,length));
	}
	
	if(length>11)
		$('#'+id).val(num.substring(0,11));
}


// Открытие новго окна без навбаров
function open_win(file) 
{
	window.open(file,'newwin','top=0, left=0, menubar=0, toolbar=0, location=0, directories=0, status=0, scrollbars=0, resizable=0');
}
 

// Аяксовый ответ от скриптов
function getAjax(url)
{
	var AjaxOBJ = false;
	
	if (window.XMLHttpRequest) 
		AjaxOBJ=new XMLHttpRequest();
	else 
	{
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP");
		var num=XmlHttpVersions.length;
		
		for (var i=0; i < num; i++) 
		{
			if(!AjaxOBJ) try {AjaxOBJ = new ActiveXObject(XmlHttpVersions[i]);}
			catch(e) {}
		}
	}
	
	if(!AjaxOBJ)
		alert('AJAX Object init error.');

	if(AjaxOBJ)
	{
		var to=document.getElementById('sm_content');
		show_sm();

		AjaxOBJ.open("GET",url);
		AjaxOBJ.onreadystatechange=function()
		{
			if(AjaxOBJ.readyState==4 && AjaxOBJ.status==200)
			{
				to.innerHTML=AjaxOBJ.responseText;
			}
			else to.innerHTML="<center>Загрузка...</center>";
		}
		AjaxOBJ.send(null);
	}
}


function check_jre()
{
	if(!navigator.javaEnabled()) {
		return false;
	} else {
		
		// is Opera? - to process Opera specific
		var isOpera = navigator.userAgent.indexOf("Opera") != -1;
		// is NS 4?
		var isNS4 = false;
		// Opera can identify itself as Netscape
		if(!isOpera) {
			isNS4 = navigator.appName.indexOf("Netscape") != -1 &&
					navigator.appVersion.substring(0, 1) == 4;
		}
		// has NS 4 Java Plug-in?
		var hasNS4JavaPlugin = false;
		for(i = 0; i < navigator.plugins.length; i++) {
			var plugin = navigator.plugins[i].name;
			if(plugin.indexOf("Java")!=-1 && plugin.indexOf("Plug")!=-1) {
				hasNS4JavaPlugin = true;
				break;
			}
		}

		// NS 4 MUST HAVE Java Plug-in
		if(isNS4 && !hasNS4JavaPlugin) {
			return false;
		}
	}
	
	return true;
}


function change_ajax_select(elem)
{
	var item = $(elem).find('option:selected').get(0);
	var item_id = parseInt($(elem).val());
	
	$(elem).parent().find("div.sub-category").remove();

	if (isNaN(item_id) || item_id == 0)
		return; 

	if ($(item).attr('child') == '1')
	{	
		var ajax_event = rand(1000000, 9000000);
		var table = $(elem).attr('table');
		
		ajax_data[ajax_event] = new Object();
		ajax_data[ajax_event]['variable'] = Object();
		ajax_data[ajax_event]['variable']['table'] = table;
		ajax_data[ajax_event]['variable']['item_id'] = item_id;
		ajax_data[ajax_event]['variable']['mode'] = 'ajax_level_select';
		ajax_data[ajax_event]['url'] = "./";
		ajax_data[ajax_event]['reload_id'] = 'select-ajax-'+table+'-parent-'+item_id;
		ajax_data[ajax_event]['indicate'] = 'select-ajax-'+table+'-parent-0';

		$(elem).parent().append("<div class='sub-category' id='select-ajax-"+table+"-parent-"+item_id+"'></div>");
		ajax_reload(ajax_event, elem);
	}
}

function rand( min, max ) {
    if( max ) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    } else {
        return Math.floor(Math.random() * (min + 1));
    }
}


function number_format( number, decimals, dec_point, thousands_sep )
{	// Format a number with grouped thousands
	// 
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)

	var i, j, kw, kd, km, minus = "";

	if(number < 0)
	{
		minus = "-";
		number = number*-1;
	}
	// input sanitation & defaults
	if( isNaN(decimals = Math.abs(decimals)) ){
		decimals = 2;
	}
	if( dec_point == undefined ){
		dec_point = ",";
	}
	if( thousands_sep == undefined ){
		thousands_sep = ".";
	}

	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

	if( (j = i.length) > 3 ){
		j = j % 3;
	} else{
		j = 0;
	}

	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


	return minus + km + kw + kd;
}

function setCookie (name, value, expires, path, domain, secure) 
{
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "; path= /") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) 
{
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

//удаляет параметр Cookie,
//установив ему время жизни 1 Января 1970 года
function DeleteCookie(name, path, domain)
{
	document.cookie = name + "=" + 
		((path) ? "; path=" + path : ";path=/") +
		((domain) ? "; domain=" + domain : "") +
	"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

