function killCA(_id_element)
{ 
//var _el=document.getElementById('search_by_code'); 
// alert("focus:"+_id_element);

//var el=document.getElementById('forfok'); 
  var key = event.keyCode || event.which;

  if (event.ctrlKey && key == 'A'.charCodeAt(0))
  {var el=document.getElementById(_id_element); 
   try {el.focus()} 
      catch(e) 
     {el.disabled=false; el.focus(); el.disabled=true}
  }

//  window.location.href=window.location.href;
}



   function preventSelection(element){  var

    preventSelection = false;
      function addHandler(element, event, handler){

    if (element.attachEvent)

    element.attachEvent('on' + event, handler);

    else

    if (element.addEventListener)

    element.addEventListener(event, handler, false);

    }


    function removeSelection(){
    if (window.getSelection) { window.getSelection
    ().removeAllRanges(); }

    else if (document.selection &&
    document.selection.clear)

    document.selection.clear();

    }

    function killCtrlA(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    if (sender.tagName.match(/INPUT|TEXTAREA/i))

    return;

    var key = event.keyCode || event.which;

    if (event.ctrlKey && key == 'A'.charCodeAt(0))
      // 'A'.charCodeAt(0)    65
    {
// o!

//   if(navigator.appName=="Opera") { window.location.reload();}

    removeSelection();
    if (event.preventDefault)
     event.preventDefault();
    else
     event.returnValue = false;
   }
   }

    //   ? ? ?

    addHandler(element, 'mousemove', function(){
     if(preventSelection)
     removeSelection();
     });

    addHandler(element, 'mousedown', function(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    preventSelection = !sender.tagName.match
    (/INPUT|TEXTAREA/i);
    });

    // ? dblclick
    // ?  ?   ?? dblclick,  
    // ? ? ?   ?
    addHandler(element, 'mouseup', function(){
    if (preventSelection)
    removeSelection();
    preventSelection = false;
    });

    // ? ctrl+A
    // ?? ?    ,  ?   ?
    //   ?   ? ? ? ?
    //   ?   document,    ?
    addHandler(element, 'keydown', killCtrlA);
    addHandler(element, 'keyup', killCtrlA);

    }


document.onselectstart = function() { return false; }

/*document.oncontextmenu = function() { return false; }
document.onmousedown   = function() { return false; }
*/

/*********************************************************************
* SwitchMenuSet script - by Roman Fanta of http://fansoft.com.ua/  E-mail: fantic-net@rambler.ru
*********************************************************************/

        var childWindowHandles = new Array();

		function open_wind(link,w,h,name) 
		{
		var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=1,toolbar=0,scrollbars=no,statusbar=0";
		childWindowHandles[childWindowHandles.length] = window.open(link,name,win);
	    for (var loop=0; loop<childWindowHandles.length; loop++) 
	    if (!childWindowHandles[loop].closed) childWindowHandles[loop].focus();
		}		
		

/*        function CloseChildWindows() 
		{
        for (var loop=0; loop<childWindowHandles.length; loop++) 
		if (!childWindowHandles[loop].closed) childWindowHandles[loop].close();
        }
 */     


function SwitchOff(obj)
{
/*    alert(ar.length); */
var ar = document.getElementById("masterdiv").getElementsByTagName("span"); //DynamicDrive.com change
   			for (var i=0; i<ar.length; i++){
				if (ar[i].id=="swich_hide")  
				ar[i].style.visibility = 'hidden';  
			}
   
}


function SwitchOn(obj)
{
/*    alert(ar.length); */	
var ar = document.getElementById("masterdiv").getElementsByTagName("span"); //DynamicDrive.com change
   			for (var i=0; i<ar.length; i++){
				if (ar[i].id=="swich_hide") 
				ar[i].style.visibility = 'visible';
			}
} 


function isInteger(s)
{
      var i; 
	s = s.toString();
      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);
         if (isNaN(c)) 
	   {
		alert("   .");
		return false;
	   }
      }
      return true;
	  
	  
}


var validate_int = function(id, description) {
  var ele = document.getElementById(id);
  var value =  (ele.value);
  if (isNaN(value)) {
    alert(description + " must be an integer");
    return false;
  }
  /* parseInt ignores anything after the leading number */
  /* Convert back to guarantee the input contains only digits */
  ele.value = value.toString();
  return true;
}

/*
function insertCopyToClipboardButton(wrapper_id) 
{ if (!document.getElementById || !document.getElementById(wrapper_id)) 
{ //       return false; } 
  else { wrapper = document.getElementById(wrapper_id); } 
  if (wrapper && wrapper.parentNode.insertBefore) 
{ button = document.createElement("a"); 
  button.setAttribute("href", "#"); 
  button.innerHTML = "  "; 
  button.onclick = function() 
   { copyToClipboard(innerText(wrapper)); 
    return false; 
   } // emulate insertAfter: 
  wrapper.parentNode.insertBefore(button, wrapper.nextSibling); 
   } 
   else { return false } 
}  



function innerText(node) 
{ // @author Dethe Elza 
// @article "XML Matters: Beyond the DOM. Tips and tricks for a friendlier DOM" 
if (node.nodeType == 3 || node.nodeType == 4) 
 { return node.data; } 
 var i; 
 var returnValue = []; 
 for (i = 0; i < node.childNodes.length; i++) 
 { returnValue.push(innerText(node.childNodes[i])); 
  } 
  return returnValue.join(''); 
}
  */

function init_visual_obj(){

				// Accordion
				//$("#accordion").accordion({ header: "h3" });
	
				// Tabs
				$('#tabs').tabs();
	

				// Dialog			
				$('#dialog').dialog({
					autoOpen: false,
					width: 600,
					buttons: {
						"Ok": function() { 
							$(this).dialog("close"); 
						}, 
						"Cancel": function() { 
							$(this).dialog("close"); 
						} 
					}
				});
				
				// Dialog Link
				$('#dialog_link').click(function(){
					$('#dialog').dialog('open');
					return false;
				});

				// Datepicker
				$('#datepicker').datepicker({
					inline: true
				});
				
				// Slider
				$('#slider').slider({
					range: true,
					values: [17, 67]
				});
				
				// Progressbar
				$("#progressbar").progressbar({
					value: 20 
				});
				
				//hover states on the static widgets
				$('#dialog_link, ul#icons li').hover(
					function() { $(this).addClass('ui-state-hover'); }, 
					function() { $(this).removeClass('ui-state-hover'); }
				);
				
			}


//********************************
function esc_select(arr)
 {
 for(var i=0;i<(arr.length);i++)
   {$(arr[i]).find("option[index=0]").attr("selected","selected");
    }
 }


function clr_obj(arr)
 {
 for(var i=0;i<(arr.length);i++)
   { $(arr[i]).html("");
    }
	 return true;
  }

//***********************

function gate_(eve,sarr,idarr,p,id,p1,p2,p3,p4,p5,p6,p7)
 {
       esc_select(sarr);
       clr_obj(idarr);
//	   p1=p1.replace(/ /g, "*");
//	   alert("gate:"+p1);
       $.post(p,{eve:eve, id:id, p1:p1,p2:p2,p3:p3,p4:p4,p5:p5,p6:p6,p7:p7},function (data){ $(id).html(data);
 			/*if (eve=="show_real_img")																											                 { alert(data);}*/
																											 });
       
 }
 //**********************




$(function(){

$("body").delegate("p","select",function(){alert('asss');})
//   $("textarea").onSelect()
   
   $("#masterdiv").css('visibility','visible');
      
   init_visual_obj();
   preventSelection(document);
		
   $("table tr[class='body']").live( "mouseenter",
    function(){ $(this).addClass('body_select').siblings().removeClass('body_select')}  );
  
   $("table tr[class='body body_select']").live( "mouseleave",
     function(){ $(this).removeClass('body_select')}   )

   $("table tr[class='body body_select']").live( "click",
     function(){ $(this).addClass('body_select_click').siblings().removeClass('body_select_click');  }   );


   $("table tr[class='last_body']").live( "mouseenter",
    function(){ $(this).addClass('last_body_select').siblings().removeClass('last_body_select')}   );
  
   $("table tr[class='last_body last_body_select']").live( "mouseleave",
     function(){ $(this).removeClass('last_body_select')}   )

   $("table tr[class='last_body last_body_select']").live( "click",
     function(){ $(this).addClass('last_body_select_click').siblings().removeClass('last_body_select_click');  }   );


  $("div [class='button_add_cart']").live( "mouseenter",
    function(){ $(this).addClass('button_add_cart_m_enter')}   );
  
  $("div [class='button_add_cart button_add_cart_m_enter']").live( "mouseleave",
     function(){ $(this).removeClass('button_add_cart_m_enter')}   );

  $("div [class='button_add_cart button_add_cart_m_enter']").live( "mousedown",
     function(){ $(this).addClass('button_add_cart_click')}   );

  $("div [class='button_add_cart button_add_cart_m_enter button_add_cart_click']").live( "mouseup",
     function(){ $(this).removeClass('button_add_cart_click')}   );

 

//============== 
  $("a[help]").live("click",function(){
      $(".containerPlus").buildContainers({
        containment:"document",
        elementsPath:"css/elements/",
        onClose:function(o){},
        onRestore:function(o){},
        onIconize:function(o){},
        effectDuration:200
      });
	  
      $('#demoContainer').mb_expand();
  
      gate_("help",[],[],"analytics.php","#mbcontainercontent",$(this).attr("id"),$(this).attr("help"));
  
    });

    $.fn.mb_expand=function(path){
      if($(this).mb_getState('closed'))
        $(this).mb_open();
      if(path)
        $(this).mb_changeContainerContent(path);

      if(!$(this).mb_getState('iconized')) return;
      $(this).mb_iconize();
    }
//============== 
//===============
   $("button").button();



   $("#tabs").bind("tabsselect", function(event, ui) {
    switch (ui.index)
	{
     case 0:
	      gate_("scroll",[],[],"analytics.php","#trash","scrl_b");  
          break; 
     case 1:
	      gate_("scroll",[],[],"analytics.php","#trash","scrl_r");  
          break; 
     case 2: 
	      gate_("scroll",[],[],"analytics.php","#trash","scrl_m");  
	         break; 
     case 3:
	     if ($("#scrl_search").length>0)
		  {
	      gate_("scroll",[],[],"analytics.php","#trash","scrl_search");  
		  }
	         break; 
}
/* 
    ui.tab     // anchor element of the selected (clicked) tab
    ui.panel   // element, that contains the selected/clicked tab contents
    ui.index   // zero-based index of the selected (clicked) tab
*/
        });

$("#logout").live("click",
              function() { 
					   gate_($(this).attr("id"),
							 [],
							 [],
							 "analytics.php",
							 "#trash",
							 "");
                         } );

///====== CHP
	var name = $("#name"),
			password = $("#password"),
			password_new = $("#password_new"),
			password_conf = $("#password_conf"),
			allFields = $([]).add(name).add(password).add(password_new).add(password_conf),
			tips = $("#validateTips");
 
		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}
 
		function checkLength(o,n,min,max) {
 
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Длинна значения " + n + " должна быть между "+min+" и "+max+".");
				return false;
			} else {
				return true;
			}
 		}

		function checkRegexp(o,regexp,n) {
 
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}
 
		}


		$("#formDialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 250,
			modal: true,
			resizable: false,
			dialogClass: alert,
			buttons: {

/*				'Отмена' : function() {
					$(this).dialog('close');
				},				*/


       'OK': function() {
		     var bValid = true;
			 allFields.removeClass('ui-state-error');
			 bValid = bValid && gate_("chng_pass",[],[],"analytics.php","#validateTips",password.val(),password_new.val(),password_conf.val());
 
			bValid = bValid && checkRegexp(password_new,/^([0-9a-zA-Z])+$/,"В пароле разрешенны только символы [a-z,0-9]");
			bValid = bValid && checkRegexp(password_conf,/^([0-9a-zA-Z])+$/,"В пароле разрешенны только символы [a-z,0-9]");
			}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
				tips.text('');
			}
		});
 
 
            $("#chng_pass").live("click",function() 
		    {
//			 $('#formDialog').load('pass_chng.php');
			 $('#formDialog').dialog('open');
		     }
			 
		 );

       
    $("#price_link").click(function() { 
					gate_("price",
							 [],
							 [],
							 "analytics.php",
							 "#trash",
							 "");}
						  
						  );

 
});

  

 function show_img(obj) { 
       var id_div=$(obj).attr("id_div");
       var src=$(obj).attr("path_image");
  	   var name=$(obj).attr("name")+src;
	   var id=$(obj).attr("id");

       if ($("#"+id_div).length==0)
		{$("#real_img").html("<div id='"+id_div+"'></div>");
//         alert(src);
	     }
       gate_("show_real_img",[],[],"analytics.php","#"+id_div, src,$(obj).attr('name'),"img_part_real","#"+id_div);
          }

 
function set_div_size_img(titl,id_div,w,h)
 {
  $(id_div).dialog({
			autoOpen: true,
			resizable: true,
			height: h,
			width: w,
			position: top,
			title: titl,
			modal: false,
			close: function() {}
			});
   return false;
 }


Array.prototype.in_array = function(_value){
for(var i = 0, l = this.length; i < l; i++) if (this[i] == _value) return i;
return -1;
}


function check_pass_expire(d,d_min,d_max)
{  if ((d < d_max)&&(d>d_min))
   {  r_d=(d_max-d);
      if (r_d<5) {t=' дня.'} else {t=' дней.'}
	 $('#validateTips').html('Вам следует поменять пароль <br>в течении <b><u>'+r_d+t+'</u></b>');
     $('#formDialog').dialog('open');
//	 alert($('#formDialog').dialog('option','buttons',[]));
	}
	
   if (d>d_max)
   { $('#validateTips').html('Закончился срок дейсвия вашего пароля. <br>Вам необходимо поменять пароль.');
	 $('.ui-dialog-titlebar-close').css('visibility','hidden');
     $('#formDialog').dialog('open');
//	 alert($('#formDialog').dialog('option','buttons',[]));
	}
	
}
