//jQuery.noConflict();

var popUps = Array();
function win_popup(name,w,h,t,sb)
{
	sb=sb+0;
        var p=window.open(name,(t!='')?t:'pop_win',"width="+w+",height="+h+",top=100,left=100,location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars="+sb+",resizable=1,fullscreen=0");
        if(p)p.focus();
        return false;
}

function checkEmail(obj){
    var str=obj.value;
    if(str=='') return true;
    if (/^([\w-~_]+\.)*[\w-~_]+@([\w-_]+\.){1,3}\w{2,4}$/.test(str))	return true;

alert("Неправильный e-mail адрес");
obj.focus();
return false;
}

function ClearAll(name){
        var obj=document.getElementById("F_"+name);

}

function zoom(name,format){
        var p=window.open('/zoom.plx?n='+name+'&amp;f='+format,'preview_window',"width=10,height=10,top=0,left=0,location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,fullscreen=0");
        if(p)p.focus();
	return false;
}

function zoomCT(file){
        var p=window.open('/zoomCT.plx?id='+file,'preview_window',"width=10,height=10,top=0,left=0,location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,fullscreen=0");
        if(p)p.focus();
	return false;
}

function ch_sz(tobj,num){
        var obj=document.getElementById("IS_"+num);
        var st=tobj.value;
        obj.innerHTML=st.split('_')[1];
	return true;
}


function mm(url){
    var img=new Image;
    img.src=url;
    return img;
}

//var imgBkYes=mm('/i/note_yes.gif');
//var imgBkNo=mm('/i/note_no.gif');

function doBk(iid,section,price) {
   var obj,img;
   if(document.all) { obj= document.all['my_note_i'];}
   else {obj=document.getElementById('my_note_i');}
    if(!isInBk(iid)) {
        addToBk(iid+'_1');
         var noteBK=document.getElementById("noteBK");
         var count=parseInt(cookieVal("noteCount"))+1;
		 if(noteBK)
		 {
		  var ender='ов';
		  if(count<5) ender='a';
		  if(count==1) ender='';
		  noteBK.innerHTML=count+' товар'+ender;
		 }
         document.cookie ="noteCount="+count+"; path=/";
         img=imgBkYes;
    } else img=imgBkNo;
    if (img && img.complete) {
        obj.src=img.src;
        showBk(iid,section);
    }
return false;
}

function showBk(iid,section){
 var obj=document.getElementById("my_note");
 var obj1=document.getElementById("ti_"+iid+"_"+section);
 var ox,oy;
 for(ox=oy=0;obj1;obj1=obj1.offsetParent)ox+=obj1.offsetLeft, oy+=obj1.offsetTop;
 obj.style.top=oy-26; obj.style.left=ox;
 obj.style.display='block';
return false;
}

function dropBk(){
 var obj=document.getElementById("my_note");
 obj.style.display='none';
}

function cookieVal(cookieName) {
    thisCookie = document.cookie.split("; ")
        for (i = 0; i < thisCookie.length; i++) {
            if (cookieName == thisCookie[i].split("=")[0]) {
                return thisCookie[i].split("=")[1];
            }
        }
    return 0;
}


function isInBk(posNum){
    var p_cookie=document.cookie;
    var cookie;
    cookie=unescape(p_cookie.substr(p_cookie.indexOf('book=')+5,p_cookie.indexOf('-NSB')-p_cookie.indexOf('book=')-4));
    return cookie.indexOf('-'+posNum+'_')==-1?false:true;
}

function addToBk(code){
    var p_cookie=document.cookie;
    var cookie;
    cookie=unescape(p_cookie.substr(p_cookie.indexOf('book=')+5,p_cookie.indexOf('-NSB')-p_cookie.indexOf('book=')-5));
    p_cookie='book='+escape(cookie+'-'+code)+'-NSB; path=/';
    document.cookie=p_cookie;
}



nodes= new Array ();
function clickOnFolder(fid)
{
   var obj,obj1;
   obj=document.getElementById("F_"+fid); obj1=document.getElementById("I_"+fid);
   if(obj)
   {
   if(nodes[fid])
   {
    nodes[fid]=false;
    obj.style.display="none";
    if(obj1)obj1.src="/img/plus.gif"
   }
   else
   {
    nodes[fid]=true;
    obj.style.display="block";
    if(obj1)obj1.src="/img/minus.gif"
   }
   }
   return false;
}

var tree_is_open = false;
function openAll(tr_){
	var el_img = document.getElementsByTagName('img');
	for( var i=0; i <el_img.length; i++) {
		if  (el_img[i].id.substr(0,2)=='I_'){
			el_img[i].src = tree_is_open?'/img/plus.gif':'/img/minus.gif';
		}
	}
	var el_div = document.getElementsByTagName('div');
	for( var i=0; i <el_div.length; i++) {
		if  (el_div[i].id.substr(0,2)=='F_'){
			el_div[i].style.display = tree_is_open?'none':'block';
		}
	}
	tree_is_open = tree_is_open?false:true;
	tr_.innerHTML = tree_is_open?'свернуть &#8593;':'раскрыть &#8595;';
	//alert();
}

function chkall(fid)
{
   var obj,obj1;
   obj=document.getElementById("F_"+fid); obj1=document.getElementById("I_"+fid);
   if(obj)
   {
    nodes[fid]=true;
    obj.style.display="block";
    if(obj1)obj1.src="/img/minus.gif"

    items= obj.childNodes;
    for (var i = 0; i < items.length; i++)
    {
 	if(items[i].nodeName== 'INPUT') items[i].checked =true;
    }

   }
   return false;
}

function clrall(fid)
{
   var obj;
   obj=document.getElementById("F_"+fid);
   if(obj)
   {
    items= obj.getElementsByTagName("input");
    for (var i = 0; i < items.length; i++)
    {
 	items[i].checked =false;
    }
   }
   return false;
}

function SelectAll(f,mark,name)
{
  for (i = 0; i < f.elements.length; i++)
   {
    var item = f.elements[i];
    if (item.name == name)
     {
      item.checked = mark;
     };
   }
return true;
}

var ldr=null;

function add(sel,v,n){
var newOpt=sel.appendChild(document.createElement('option'));
newOpt.text=n;
newOpt.value=v;
}

function chan(f,name,qw,parm)
{
 if(ldr&&ldr.readyState!=0) { ldr.abort() }
 ldr=selector();
 if(ldr)
 {
 	name.length = 0;
 	var now = new Date();
 	ldr.open("GET","/selector.plx?q="+parm+"&sel="+qw+"&t="+now.getSeconds(),true);
	ldr.onreadystatechange=function()
	{
	if(ldr.readyState==4 && ldr.responseText)
		{
			eval(ldr.responseText);
		}
	};
	ldr.send(null)
 }
}


function selector()
{
	var A=null;
	try{A=new ActiveXObject("Msxml2.XMLHTTP")}
	catch(e){try{A=new ActiveXObject("Microsoft.XMLHTTP")}
	catch(oc){A=null}}
	if(!A&&typeof XMLHttpRequest!="undefined") {A=new XMLHttpRequest()}
	return A
}

function dl()
{
	return confirm('Подтверждаете удаление?');
}

function SendBill(v1)
{
	return confirm('Выписать счет на сумму '+v1+'?');
}

function showSubarea(form,subarea,area) {
    var A=null;
    if (area>0) {
      chan(form,subarea,'yd_subarealist',area);
      if (subarea.hasChildNodes()) {
        //document.getElementById('subareaid').disabled=false;
        //document.getElementById('subareatr1').style.display='block';
        //document.getElementById('subareatr2').style.display='block';

      }
      else {
        //document.getElementById('subareatr1').style.display='none';
        //document.getElementById('subareatr2').style.display='none';
        //document.getElementById('subareaid').disabled=true;

      }
    }
    else {
      //document.getElementById('subareatr1').style.display='none';
      //document.getElementById('subareatr2').style.display='none';
      //document.getElementById('subareaid').disabled=true;

    }
    return false;
}
function ShowHide(handler,anc,dx,dy,absx,absy,func)
{
	dx=dx-70;
	dy=dy-130;
		var inArray;
		element = document.getElementById(handler).style;
		if (element.display == "none" || !element.display){

if(anc)
{
 var obj=document.getElementById(handler);
 var obj1=document.getElementById(anc);
if(obj1){
 var ox,oy;
 for(ox=oy=0;obj1;obj1=obj1.offsetParent) ox+=obj1.offsetLeft, oy+=obj1.offsetTop;
 if(dx)ox=ox+dx;
 if(dy)oy=oy+dy;
 if(absx)ox=absx;
 if(absy)oy=absy;
 obj.style.top=oy+"px"; obj.style.left=ox+"px";
}else{

 pTop = document.documentElement.clientHeight>dy?document.documentElement.clientHeight-dy:0;
 obj.style.top=document.documentElement.scrollTop+(pTop)/2+"px";
 pLeft = document.documentElement.clientWidth>dx?document.documentElement.clientWidth-dx:0;
 obj.style.left=document.documentElement.scrollLeft+(pLeft)/2+"px";
	}
}

			element.display = "block";
			for (var i = 0; i <popUps.length; i++) {
				if (popUps[i].hwnd == handler){
					inArray = true;
 				}
			}
			if (!inArray) {
				popUps.push({hwnd:handler,func:func,status:true});
			}
			click = true;
		}
		else {
			element.display = "none";
			for (var i = 0; i <popUps.length; i++) {
				if (popUps[i].hwnd == handler){
					popUps[i].status= false;
 				}
			}
			click = true;
		}
return false;
}
function cancel_bubble(evt) {
	evt = evt || window.event;
	evt.cancelBubble = true;
}



/*----- object functions  -----*/

function obj_clone(object)
{
    if (typeof(object) != "object") return object;
    var newObject = object.constructor();
    for (objectItem in object) {
        newObject[objectItem] = obj_clone(object[objectItem]);
    }
    return newObject;
}



//////////////////////////////////////////////////////////////
/////////////// ADVERTISEMENT CONSTRUCTOR ////////////////////
//////////////////////////////////////////////////////////////


Colors = function (objectId, inputTextId, styleColor, pallete)
// конструктор
{

	this._object = document.getElementById(objectId);
	this._objectId = objectId;
	this.inputText = document.getElementById(inputTextId);
	this.inputTextId = inputTextId;
	this.styleColor = styleColor;
	//alert('this.oldColor = Colors.rgb2hex(this._object.style.'+styleColor+')');
	eval('this.oldColor = Colors.rgb2hex(this._object.style.'+styleColor+')');
	this.inputText.value = this.oldColor;

	this.pallete = pallete;

}

Colors.prototype.show = function ()
// рисуем палитру
{

	var table = '<span id="allcolorselementsselect'+this.inputTextId+'" onclick="document.getElementById(\'allcolorselements'+this.inputTextId+'\').style.display=\'block\'; document.getElementById(\'allcolorselementslink'+this.inputTextId+'\').focus();" style="cursor: pointer;"><img src="'+this.outImage+'" title="Выбрать цвет из палитры" style="position:relative; top:2px;" onmouseover="this.src=\''+this.overImage+'\'" onmouseout="this.src=\''+this.outImage+'\'" /></span>';
	table += '<input id="setc'+this.inputTextId+'" type="hidden" value="0" />';
	table += '<input id="oldColor'+this.inputTextId+'" type="hidden" value="#'+this.oldColor+'" />';
	table += '<a id="allcolorselementslink'+this.inputTextId+'" href="#" onclick="return false;" onblur="document.getElementById(\'allcolorselements'+this.inputTextId+'\').style.display=\'none\'; if (document.getElementById(\'setc'+this.inputTextId+'\').value!=\'1\') Colors.changecolor(document.getElementById(\'oldColor'+this.inputTextId+'\').value, \''+this._objectId+'\', \''+this.inputTextId+'\', \''+this.styleColor+'\'); document.getElementById(\'setc'+this.inputTextId+'\').value=\'0\'; ">';
	table += '<div id="allcolorselements'+this.inputTextId+'" style="width: '+this.allwidth+'px; cursor: pointer; display: none; position: absolute; z-index:1000; background-color:#bbb; border:solid 1px #bbb;">';

	for (var i=1, c=0; i<=this.rows; i++)
	{
		//table += '<tr height="20">';
		for (var j=1; j<=this.cols; j++)
		{
			table += '<div style="background:'+this.pallete[c++]+'; float:left; width:'+this.width+'px; height:'+this.width+'px; margin:'+this.border+'px; border:solid '+this.border+'px #000;" onmousedown="document.getElementById(\'setc'+this.inputTextId+'\').value=\'1\'; document.getElementById(\'oldColor'+this.inputTextId+'\').value=this.style.backgroundColor;" onmousemove="Colors.changecolor(this.style.backgroundColor, \''+this._objectId+'\', \''+this.inputTextId+'\', \''+this.styleColor+'\');" onmouseover="this.style.border=\'solid '+this.border+'px #ffff00\'" onmouseout="this.style.border=\'solid '+this.border+'px #000\';"></div>';
		}
		table += '<div style="clear:both;"></div>';
	}
	table += '</div></a>';

	//document.writeln(table);
	return table;
}


Colors.rgb2hex = function (rgb) {
// вспомогательная функция преобразование из формата rgb(0,0,0) в hex

  if (!rgb)
  {
    return '';  //000000
  }
  if (rgb.substring(0,1)=="#")
  {
    return rgb.substring(1);
  }
  else
  {
	  var s,i,h='', x='0123456789abcdef';
	  var c = rgb.substring(4);
	  c = c.substring(0, c.length-1);


	  if(c){
	    s=c.split(',');
	    for (i=0; i < 3; i++){
	      n  = parseInt(s[i]);
	      h += x.charAt(n>>4) + x.charAt(n&15);
	    }
	  return h;
	  }
  }
}

Colors.changecolor = function (thiscolor, _object, inputText, styleColor)
{
	eval('document.getElementById(_object).style.'+styleColor+' = thiscolor');
	document.getElementById(inputText).value = Colors.rgb2hex(thiscolor);
}

Colors.setup = function (params) {
	function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };
	param_default("rows",			5);
	param_default("cols",			12);
	param_default("width",			20);
	param_default("border",			1);
	param_default("styleColor",		"color");
	param_default("inputTextId",	null);
	param_default("objectId",		null);
	param_default("pallete",        new Array (
	'#FFFFCC',	'#FFFF66',	'#FFCC66',	'#F2984C',	'#E1771E',	'#B47B10',	'#A9501B',	'#6F3C1B',	'#804000',	'#CC0000',	'#940F04',	'#660000',
	'#C3D9FF',	'#99C9FF',	'#66B5FF',	'#3D81EE',	'#0066CC',	'#6C82B5',	'#32527A',	'#2D6E89',	'#006699',	'#215670',	'#003366',	'#000033',
	'#CAF99B',	'#80FF00',	'#00FF80',	'#78B749',	'#2BA94F',	'#38B63C',	'#0D8F63',	'#2D8930',	'#1B703A',	'#11593C',	'#063E3F',	'#002E3F',
	'#FFBBE8',	'#E895CC',	'#FF6FCF',	'#C94093',	'#9D1961',	'#800040',	'#800080',	'#72179D',	'#6728B2',	'#6131BD',	'#341473',	'#400058',
	'#FFFFFF',	'#E6E6E6',	'#CCCCCC',	'#B3B3B3',	'#999999',	'#808080',	'#7F7F7F',	'#666666',	'#4C4C4C',	'#333333',	'#191919',	'#000000'
	));
	param_default("outImage",		"rgb.gif");
	param_default("overImage", 		"on_rgb.gif");


	var col = new Colors(params.objectId, params.inputTextId, params.styleColor, params.pallete);

	col.rows = params.rows;
	col.cols = params.cols;
	col.width = params.width;
	col.border = params.border;
	col.allwidth = col.cols*(col.width+col.border*4)+col.border;
	col.outImage = params.outImage
	col.overImage = params.overImage

	//col.show();
 	//return col;

 	//return col.show();
 	res = col.show();
 	document.getElementById(params.inputTextId+'_pic').innerHTML = res;
 	return res;
}

// id -  1_2_3
// 1 - тип (рыба f, поле i)
// 2 - объект ( пр. tbl)
// 3 - сво-во (пр. b - border)

function BGEnabled(tr_){
	fish_id = 'f'+tr_.id.substr(1);
	input_id = 'i'+tr_.id.substr(1);
	if (tr_.checked){
		//document.getElementById(input_id).disabled = false;
		document.getElementById(input_id).readOnly = false;
		document.getElementById(fish_id).style.backgroundColor = '#'+document.getElementById(input_id).value;
		document.getElementById('allcolorselementsselect'+input_id).style.visibility = 'visible';
		//document.getElementById('allcolorselementsselect'+input_id).style.display = 'block';
	}else{
		document.getElementById(input_id).readOnly = true;
		document.getElementById(fish_id).style.backgroundColor = 'transparent';
		document.getElementById('allcolorselementsselect'+input_id).style.visibility = 'hidden';
		//document.getElementById('allcolorselementsselect'+input_id).style.display = 'none';
	}

}

function BDEnabled(tr_){

	fish_id = 'f'+tr_.id.substr(1);
	if(fish_id.lastIndexOf ('_') != '-1'){
		fish_id = fish_id.substr(0,fish_id.lastIndexOf ('_'));
	}

	input_id = 'i'+tr_.id.substr(1);
	if (tr_.checked){
		document.getElementById(input_id).readOnly = false;
		document.getElementById(fish_id).style.borderColor = '#'+document.getElementById(input_id).value;
		document.getElementById(fish_id).style.borderWidth = '1px';
		document.getElementById('allcolorselementsselect'+input_id).style.visibility = 'visible';
		//document.getElementById('allcolorselementsselect'+input_id).style.display = 'block';
	}else{
		document.getElementById(input_id).readOnly = true;
		document.getElementById(fish_id).style.borderWidth = '0';
		document.getElementById('allcolorselementsselect'+input_id).style.visibility = 'hidden';
		//document.getElementById('allcolorselementsselect'+input_id).style.display = 'none';
	}

}


function ChTC(tr_){
	first_ind = tr_.id.indexOf('_');
	last_ind = tr_.id.lastIndexOf('_');
	if(first_ind == last_ind){
		fish_id = 'f'+fish_id.substr(1);
	}else{
		fish_id = tr_.id.substr(0,last_ind);
		fish_id = 'f'+fish_id.substr(1);
	}
	document.getElementById(fish_id).style.color = '#'+tr_.value;
}
//
function ChTCA(tr_,aim){
	 ChTC(tr_);
	document.getElementById(aim).style.color = '#'+tr_.value;
}

function ChBG(tr_){
	fish_id = 'f'+tr_.id.substr(1);
	document.getElementById(fish_id).style.backgroundColor = '#'+tr_.value;
}
function ChBC(tr_){
	first_ind = tr_.id.indexOf('_');
	last_ind = tr_.id.lastIndexOf('_');
	if(first_ind == last_ind){		fish_id = 'f'+fish_id.substr(1);
	}else{		fish_id = tr_.id.substr(0,last_ind);
		fish_id = 'f'+fish_id.substr(1);
	}
	document.getElementById(fish_id).style.borderColor = '#'+tr_.value;
}
function ChF(tr_){
	buf = false;
	fish_id = 'f'+tr_.id.substr(1);
	if(fish_id.lastIndexOf ('_') != '-1'){
		style_pointer = fish_id.substr(fish_id.lastIndexOf ('_')+1);
		fish_id = fish_id.substr(0,fish_id.lastIndexOf ('_'));
	}
	input_id = 'i'+tr_.id.substr(1);
    fish_ = document.getElementById(fish_id);
    input_ = document.getElementById(input_id);


	val_pref = '';
	if (style_pointer == 'ff') style_name = 'fontFamily';
	if (style_pointer == 'fs') {
		style_name = 'fontSize';
		val_pref = '';
		// удаляем пробел (11 px - 11px) из значения
		buf = input_.options[input_.selectedIndex].value;
		input_.options[input_.selectedIndex].value = buf.replace(' ','');
		// up header size on 2 px
		document.getElementById('f_header').style.fontSize = parseInt(input_.options[input_.selectedIndex].value)+2+'px';
		// down site_name size on 1 px
		document.getElementById('f_site').style.fontSize = parseInt(input_.options[input_.selectedIndex].value)-1+'px';

		//document.getElementById('f_mm').style.fontSize = input_.options[input_.selectedIndex].value+'px';

	}

	//alert(input_.options[input_.selectedIndex].value+'"'+val_pref+'"');
	//alert(input_.options[input_.selectedIndex].value);
	eval('fish_.style.'+style_name+' = input_.options[input_.selectedIndex].value;');
	// возвращаем страрое значение (если его форматировали)
	if (buf) input_.options[input_.selectedIndex].value = buf;
}

// Для конструктора блоков с товарами из ГМ

function checkboxChanger(el) {
	if (el.checked) el.value=1;
	else el.value=0;
}

function GMprepare(form) {
	checkboxChanger(document.getElementById("c_tbl"));
	checkboxChanger(document.getElementById("c_tbl_b"));
	for(i=0;i<form.elements.length;i++) {
		name=form.elements[i].name;
		value=form.elements[i].value;
		if (name && value!='')	variables[name] = value;
	}
	makeUrlVars();

//	urlVars=makeUrlVars();
	document.getElementById("jscode").value=makeJSCode();
}

function makeJSCode(mode) {
	text='<script type="text/javascript">\n';

	for( var key in variables ) {
		text+="var " + key + " = '" + variables[key] + "';\n";
	}

//	text+="GMdraw();";
//	else {
//		mode="usual";
//		text+="window.location.reload();";
//	}
enc=document.getElementById("encZ").options[document.getElementById("encZ").value-1].text;
	text+='</script>\n<script type="text/javascript" src="http://'+ areaName +'/gmshow/'+ ofGroup +'/'+urlVars+'/" charset="'+ enc +'"></script>\n';
	return text;
}

function makeUrlVars() {
	urlVars="";
	if (variables["num_blocks"] && variables["num_blocks"] != '') {
		variables["num_blocks"]=parseInt(variables["num_blocks"]);
		urlVars+="l"+variables["num_blocks"];
		delete variables["num_blocks"];
	}
	if (variables["encoding"] && variables["encoding"] != '') {
		variables["encoding"]=parseInt(variables["encoding"]);
		urlVars+="e1";//+variables["encoding"];
//		delete variables["encoding"];
	}
	if (variables["show_picture"] && variables["show_picture"] != '') {
		variables["show_picture"]=parseInt(variables["show_picture"]);
		if (variables["show_picture"]==2) urlVars+="p"+variables["show_picture"];
	}
//	if (variables["orientation"] && variables["orientation"] != '') {
//		variables["orientation"]=parseInt(variables["orientation"]);
//		urlVars+="o"+variables["orientation"];
//		delete variables["orientation"];
//	}
	if (variables["item_ids"] && variables["item_ids"] != '') {

			variables["item_ids"]=variables["item_ids"].split(",");
			for(i=0;i<variables["item_ids"].length;i++) {
				variables["item_ids"][i]=parseInt(variables["item_ids"][i]);
				if (variables["item_ids"][i]==0) delete variables["item_ids"][i];
			}
			urlVars+="i" + variables["item_ids"].join("i");
			delete variables["item_ids"];
			delete variables["catalogue_ids"];
	} else {
		if (variables["catalogue_ids"] && variables["catalogue_ids"] != '') {
		variables["catalogue_ids"]=variables["catalogue_ids"].split(",");
		for(i=0;i<variables["catalogue_ids"].length;i++) {
			variables["catalogue_ids"][i]=parseInt(variables["catalogue_ids"][i]);
			if (variables["catalogue_ids"][i]==0) delete variables["catalogue_ids"][i];
		}
		urlVars+="c" + variables["catalogue_ids"].join("c");
		delete variables["item_ids"];
		}
	}
	delete variables["e"];
//	return urlVars;
}

function GMpreview() {
	if(newWindow) newWindow.close();
//	if(typeof(newWindow) != 'undefined') newWindow.close();
	unset=0;
	if(!variables["font_name"]) {
		unset=1;
		variables["font_name"]="Tahoma, sans-serif";
	}
	var d=new Date();
	wname="GMpreview"+d.getTime();
	newWindow=window.open("",wname,"");
//	newWindow.document.write("<html><head><title>Предпросмотр</title></head><body onload='alert(document.getElementsByTagName(\"table\").length)'>");
	newWindow.document.write("<html><head><title>Предпросмотр</title></head><body onload='document.getElementsByTagName(\"table\")[2].innerHTML=\"\"'>");
	newWindow.document.write(makeJSCode());
	newWindow.document.write("</body><html>");
	if (unset==1) variables["font_name"]='';
	return false;
}

function ch_var(name,value) {
	if (name=='show_picture') {
		im=document.getElementById("itemImage").style;
		if (value>0) {
			im.visibility="visible";
			im.display="block";
		}
		else {
			im.visibility="hidden";
			im.display="none";
		}
	}
}


var UserColorScheme;
var IsUserScheme = 1;

function SetColorScheme(tr_){
	schemes = {
				1:{ site_bg:'ffffff',
					block_bg:'ffffff',
					border:'ffc89c',
					header:'cc0000',
					text:'000000',
					site_name:'a9501b'
					},
				2:{ site_bg:'ffffff',
					block_bg:'ffffff',
					border:'66b5ff',
					header:'3d81ee',
					text:'3d81ee',
					site_name:'66b5ff'
					},
				3:{ site_bg:'ffffff',
					block_bg:'000000',
					border:'ffffff',
					header:'ffffff',
					text:'ffffff',
					site_name:'ffffff'
					}

			  }

	scheme_id = tr_.options[tr_.selectedIndex].value;
	//alert(scheme_id);

	// переключение на предустановленную схему
	if (scheme_id != '0'){
		// сохранение юзерской схемы
		if (IsUserScheme == 1){
			UserColorScheme = {
				site_bg:document.getElementById('i_bg').value,
				block_bg:document.getElementById('i_tbl').value,
				border:document.getElementById('i_tbl_b').value,
				header:document.getElementById('i_header_tc').value,
				text:document.getElementById('i_text_tc').value,
				site_name:document.getElementById('i_site_tc').value
			}

			IsUserScheme = 0;
		}

		//document.getElementById('f_bg').style.backgroundColor = schemes[scheme_id][0];
		document.getElementById('i_bg').value = schemes[scheme_id]['site_bg'];
		document.getElementById('i_tbl').value = schemes[scheme_id]['block_bg'];
		if (schemes[scheme_id]['block_bg'] != "ffffff")	document.getElementById('c_tbl').checked = 1;
		document.getElementById('i_tbl_b').value = schemes[scheme_id]['border'];
		document.getElementById('i_header_tc').value = schemes[scheme_id]['header'];
		document.getElementById('i_text_tc').value = schemes[scheme_id]['text'];
		document.getElementById('i_site_tc').value = schemes[scheme_id]['site_name'];

	// перключение на юзерскую схему
	}else{
		document.getElementById('i_bg').value = UserColorScheme['site_bg'];
		document.getElementById('i_tbl').value = UserColorScheme['block_bg'];
		document.getElementById('i_tbl_b').value = UserColorScheme['border'];
		document.getElementById('i_header_tc').value = UserColorScheme['header'];
		document.getElementById('i_text_tc').value = UserColorScheme['text'];
		document.getElementById('i_site_tc').value = UserColorScheme['site_name'];

		IsUserScheme = 1;

	}

	ApplyFieldsSettings();
}



// приминение настроек (загруженных в поля) к рыбе.
function ApplyFieldsSettings(){
// inputs id array
var inputs = ['i_bg','c_tbl','c_tbl_b','i_td_ff','i_td_fs','i_header_tc','i_text_tc','i_site_tc'];


	for (var i=0;i<inputs.length;i++){
		id_ = inputs[i];

		first_ind = id_.indexOf('_');
		last_ind = id_.lastIndexOf('_');

		input_ = false;
		fish_ = false;
		style_name = false;
		checkbox_ = false;
		val_pref = '';
		select = false;
		style_pointer = false;
		buf = false;

		// нет ни типа ни сво-ва
		if (first_ind == '-1'){
			cl_id = id_;
			fish_ = document.getElementById('f_'+id_);
			input_ = document.getElementById('i_'+id_);
			style_name = 'backgroundColor';
		// есть тип
		}else if (first_ind == last_ind){
			type_ = id_.substr(0,first_ind);
			cl_id = id_.substr(first_ind+1);

			if (type_ == 'i'){
				input_ = document.getElementById('i_'+cl_id);
				fish_ = document.getElementById('f_'+cl_id);
				style_pointer = 'bg';
				style_name = 'backgroundColor';
			}

			if (type_ == 'c'){
				checkbox_ = document.getElementById(id_);
				input_id = 'i_'+cl_id;
				input_ = document.getElementById('i_'+cl_id);
				fish_ = document.getElementById('f_'+cl_id);
				style_pointer = 'bg';
				style_name = 'backgroundColor';
			}

		// есть тип и св-во
		}else{
			type_ = id_.substr(0,first_ind);
			style_pointer = id_.substr(last_ind+1);
			cl_id = id_.substr(first_ind+1);
			cl_id = cl_id.substr(0,cl_id.indexOf('_'));

			//alert(type_+' - '+cl_id+' - '+style_pointer)

			if (type_ == 'i'){
				input_ = document.getElementById('i_'+cl_id+'_'+style_pointer);
				fish_ = document.getElementById('f_'+cl_id);
			}

			if (type_ == 'c'){
				checkbox_ = document.getElementById('c_'+cl_id+'_'+style_pointer);
				input_id = 'i_'+cl_id+'_'+style_pointer;
				input_ = document.getElementById('i_'+cl_id+'_'+style_pointer);
				fish_ = document.getElementById('f_'+cl_id);
			}

			if (style_pointer == 'ff') {
				style_name = 'fontFamily';
				select = 1;
			} else if (style_pointer == 'fs'){
				style_name = 'fontSize';
				val_pref = '';
				select = 1;
				// удаляем пробел (11 px - 11px) из значения
				buf = input_.options[input_.selectedIndex].value;
				input_.options[input_.selectedIndex].value = buf.replace(' ','');
				// up header size on 2 px
				document.getElementById('f_header').style.fontSize = parseInt(input_.options[input_.selectedIndex].value)+2+'px';
				// down site_name size on 1 px
				document.getElementById('f_site').style.fontSize = parseInt(input_.options[input_.selectedIndex].value)-1+'px';

			}else if (style_pointer == 'b'){
				style_name = 'borderColor';
			}else if (style_pointer == 'tc'){
				style_name = 'color';
			} else {
				style_pointer = 'bg';
				style_name = 'backgroundColor';
			}


		} // else

		// если поле с боксом
		if (checkbox_){
			// если бокс чекед
			if (checkbox_.checked){
				//приминение настроек
				// если поле select
				if(select){
					eval('fish_.style.'+style_name+' = input_.options[input_.selectedIndex].value+"'+val_pref+'";');
				// если поле input type=text
				}else{
					eval('fish_.style.'+style_name+' = input_.value');
				}
			// если не чекед
			}else{
				// блокируем возможность изменения параметров
				input_.readOnly = true;
				document.getElementById('allcolorselementsselect'+input_id).style.visibility = 'hidden';
				if (style_pointer == 'b') fish_.style.borderWidth = '0';
				if (style_pointer == 'bg') fish_.style.backgroundColor = 'transparent';
			}

		// если нет бокса
		}else{
			//приминение настроек
			// если поле select
			if(select){
				eval('fish_.style.'+style_name+' = input_.options[input_.selectedIndex].value+"'+val_pref+'";');

				// возвращаем страрое значение (если его форматировали)
				if (buf) input_.options[input_.selectedIndex].value = buf;

			// если поле input type=text
			}else{
				eval('fish_.style.'+style_name+' = input_.value');
			}

		} // else




	} // for
} // function

//////////////////////////////////////////////////////////////
/////////// END of ADVERTISEMENT CONSTRUCTOR /////////////////
//////////////////////////////////////////////////////////////


function toClipBoard(content){
	content = content.replace(/&lt;br&gt;/ig,"\r\n");
	content = content.replace(/&lt;\/?span(.*?)&gt;/ig,"");
	content = content.replace(/&amp;lt;/ig,"&lt;");
	content = content.replace(/&amp;gt;/ig,"&gt;");
	copyToClipboard(content);

	//content = content.replace(/&amp;/ig,'&amp;amp;');
	//content = content.replace(/"/ig,'&amp;quot;');
	//content=escape(content);
	//alert(content);
    //copyToClipboardSFW(content);
}

function checkChildTree(tr_,id_){
	if ($(tr_).is(':checked')){
		$('#'+id_+' input:checkbox').attr('disabled','disabled');
		$('#'+id_+' input:checkbox').attr('checked','checked');
	}else{
		$('#'+id_+' input:checkbox').removeAttr('checked');
		$('#'+id_+' input:checkbox').removeAttr('disabled');
	}
}


/* JQUERY AJAX */

function jajax(url_,obj_){
 $.ajax({
   type: "POST",
   url: url_,
   data: obj_,
   dataType: 'xml',
   success: function(resp_){

   	  $('sajax',resp_).each(function(){

   	      $('replace',this).each(function(){
   	      	   var id_ = $('id',this).text();
   	      	   var val_ = $('data',this).text();
   	      	   $('#'+id_).html(val_);
   	      });

   	      $('add',this).each(function(){
   	      	   var id_ = $('id',this).text();
   	      	   var val_ = $('data',this).text();
   	      	   $('#'+id_).append(val_);
   	      });

   	      $('remove',this).each(function(){
   	      	   var id_ = $('id',this).text();
   	      	   $('#'+id_).remove();
   	      });

   	      $('hide',this).each(function(){
   	      	   var id_ = $('id',this).text();
   	      	   $('#'+id_).css("display","none");
   	      });

   	      $('show',this).each(function(){
   	      	   var id_ = $('id',this).text();
   	      	   $('#'+id_).css("display","block");
   	      });

   	      $('javascript',this).each(function(){
   	      	   var text_ = $(this).text();
   	      	   eval(text_);
   	      });

   	  });
   }

 });
}

/* /JQUERY AJAX */

// on document ready function

$(function() {

	//$("#PCTree").draggable({ handle: '#PCTree_anc' });

	$('div.draggable').draggable({ handle: '.draggable_anc' });

});



