var IE = (navigator.appName == "Microsoft Internet Explorer");
var OP= (navigator.appName == "Opera");
var NS= (navigator.appName == "Netscape");
var debug=false;
function ajax(link,div,param,loader,dofunction){
        var xmlhttp=false;
        //if(link.indexOf('raport') + 1) {
        //  debug=true;
        //}
        //alert(dofunction);
        //alert(link);
        if (div!=null&&parent.document.getElementById(div)&&(parent.document.getElementById(div).tagName=='DIV'||parent.document.getElementById(div).tagName=='TD')){
          if (loader==null||loader==undefined||loader=="") loader='/content/image/design/loader.gif';
          parent.document.getElementById(div).innerHTML = "<center><table width='100%' class='no'><tr><td align='right' style='text-align:right; vertical-align:middle;' width='40%'><img src='"+loader+"' alt='' title=''/></td><td style='text-align:left;padding-left:10px; vertical-align:middle;' width='60%' align='left'>подождите...</td></tr></table></center>";
        } else if (div!=null&&parent.document.getElementById(div)){
          parent.document.getElementById(div).setAttribute('style','opacity:0.6;');
          if (parent.document.getElementById(div).style.setAttribute) parent.document.getElementById(div).style.setAttribute("filter", "alpha(opacity=60);");
        }
        method="POST";

		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			try {
				xmlhttp = new XMLHttpRequest();
			} catch (e) {
				xmlhttp = false;
			}
		}
	    if (!xmlhttp) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            	} catch (e) {
                try {
                       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {}

		}
	    }

		xmlhttp.open(method, link, true);
		xmlhttp.setRequestHeader("X-REQUESTED-WITH", "XMLHttpRequest");
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=WINDOWS-1251");
		xmlhttp.onreadystatechange = function()
        {
	        if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200){
                    if (debug)
                        alert(xmlhttp.responseText);
                    if (xmlhttp.responseText!=''){
                        var answer=eval("("+xmlhttp.responseText+")");
    	                if (div!=null&&parent.document.getElementById(div)){
            	            if (div!=null&&parent.document.getElementById(div)&&xmlhttp.responseText!='true'){
            	                if ((parent.document.getElementById(div).tagName=='SPAN'||parent.document.getElementById(div).tagName=='A')){
    	                           parent.document.getElementById(div).setAttribute('style','opacity:1;');
    	                           if (parent.document.getElementById(div).style.setAttribute) parent.document.getElementById(div).style.setAttribute("filter", "alpha(opacity=100);");
    	                        }
    	                        if (answer.className!=undefined){
    	                            parent.document.getElementById(div).className=answer.className;
    	                        }
    	                        if (answer.tooltip!=undefined){
    	                            parent.document.getElementById(div).setAttribute('clhint',answer.tooltip);
    	                        }
    	                        if (answer.result!=undefined){
    	                          parent.document.getElementById(div).innerHTML = answer.result;
    	                          if (answer.result=='')
    	                            parent.document.getElementById(div).parentNode.removeChild(parent.document.getElementById(div));
    	                        }
                                }
    			        }
                        if (answer.hide!=undefined) {parent.document.getElementById(answer.hide).style.visibility="hidden";}
                        if (answer.show!=undefined) {parent.document.getElementById(answer.show).style.visibility="visible";}
                        if (answer.alert!=undefined) {alert(answer.alert);}
                        if (answer.reload!=undefined) {window.location.reload(true);}
                        if (answer.relocate!=undefined) {document.location = answer.relocate;}
                        if (dofunction!=undefined) dofunction(answer);
                    }
                    xmlhttp=false;
                } else {
                  xmlhttp=false;
                }
            }
        }

		xmlhttp.send(param);
}

function selectajax(link,param,select_id){
        var xmlhttp=false;
        if (select_id!=null&&parent.document.getElementById(select_id)){
          parent.document.getElementById(select_id).options.length=0;
          parent.document.getElementById(select_id).options.length=1; //обрезаем длину селекта до 1
          parent.document.getElementById(select_id).options[0]=new Option("Идет загрузка", 0); //создаем запись что нет элементов
          parent.document.getElementById(select_id).disabled=1; //ставим аттрибует дисаблед
        }
        method="POST";


		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			try {
				xmlhttp = new XMLHttpRequest();
			} catch (e) {
				xmlhttp = false;
			}
		}
	    if (!xmlhttp) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            	} catch (e) {
                try {
                       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {}

		}
	    }

		xmlhttp.open(method, link, true);
		xmlhttp.setRequestHeader("X-REQUESTED-WITH", "XMLHttpRequest");
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=WINDOWS-1251");
		xmlhttp.onreadystatechange = function()
        {
	        if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200){
    	            if (select_id!=null&&parent.document.getElementById(select_id)){
                        parent.document.getElementById(select_id).options.length=0;
                        parent.document.getElementById(select_id).disabled=0;
                        var answer= xmlhttp.responseXML.documentElement;
                        var options = answer.getElementsByTagName("option");
                        for(i=0;options.length;i++){
                           var text = options[i].firstChild.data; //получаем название элемента
                           var value= options[i].getAttribute("value"); //его номер
                           parent.document.getElementById(select_id).options[i]=new Option(text, value); //добавляем option
                        }
                    }
                    xmlhttp=false;
                } else {
                  xmlhttp=false;
                }
            }
        }
		xmlhttp.send(param);
}


var clevercrop = { // NAMESPACE
    processImage : function(id,preview_id) {
        return new this.construct(id);
    }
};

clevercrop.construct = function(id) { // Constructor
    // Vars
    this.id = id;
        // Image data
    this.iWidth = 0;
    this.iHeight = 0;
    this.iMaxWidth = 0;
    this.iMaxHeight = 0;
    this.iMinWidth = 0;
    this.iMinHeight = 0;
    this.iTop = 0;
    this.iLeft = 0;
    this.iRate = 0;
    this.objx = 0;
    this.objy = 0;
        // Crop block data
    this.cropWidth = 150;
    this.cropHeight = 150;
    this.cropTop = false;
    this.cropLeft = false;
    this.cropMinWidth= 100;
    this.cropMinHeight = 100;
    this.cropBackground = false;
        // Move
    this.X0 = 0;
    this.Y0 = 0;
        // Resize div data
    this.resizeWidth = 8;
    this.resizeHeight = 8;
    //this.resizeTop = 0;
    //this.resizeLeft = 0;
        // Resize move
    this.iBuferWidth = 0;
    this.iBuferHeight = 0;
    // Flags
    this.cropMoveState = false;
    this.resizeTRMoveState = false;
    this.resizeBRMoveState = false;
    this.resizeTLMoveState = false;
    this.resizeBLMoveState = false;
    this.saveProportions = true;
    this.stopSelection = true;
    this.debugMode = true;
    // Handlers
    this.onUpdate = null;
    // Nodes
    this.image = null;
    this.crop = null;
    this.resizeTL = null;
    this.resizeBR = null;
    this.resizeBL = null;
    this.resizeTR = null;
}

clevercrop.construct.prototype = {
// Const
    ERRORS : {
        1 : "Ошибка инициализации картинки",
        2 : "Картинка не найдена",
        3 : "Указанный элемент не является картинкой",
        4 : "Не установлена функция onUpdate",
        5 : "Элемент body не найден"
    },
// Methods
    // Default
    addMouseHandler : function(object, event, handler, useCapture) {
        if (object.addEventListener) {
            object.addEventListener(event, handler, useCapture ? useCapture : false);
        } else if (object.attachEvent) {
            object.attachEvent('on' + event, handler);
        } else alert(this.errorArray[9]);
    },
    defPosition : function(event) {
        var x = y = 0;
        if (document.attachEvent != null) {
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
        }
        if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }
        if (x<this.iLeft) x=this.iLeft;
        if (y<this.iTop) y=this.iTop;
        if (x>this.iLeft+this.iWidth) x=this.iLeft+this.iWidth;
        if (y>this.iTop+this.iHeight) y=this.iTop+this.iHeight;
        return {x:x, y:y};
    },
    absPosition : function(obj) {
        var x = y = 0;
        while(obj.offsetParent) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return {x:x, y:y};
    },
    domReady : function(i) { /* Copyright http://ajaxian.com/ */
        var u =navigator.userAgent;
        var e=/*@cc_on!@*/false;
        var st = setTimeout;
        if (/webkit/i.test(u)) {
            st(
                function() {
                    var dr=document.readyState;
                    if(dr=="loaded"||dr=="complete") i();
                    else st(arguments.callee,10);
                },
                10
            );
        } else if ((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))) {
            document.addEventListener("DOMContentLoaded", i, false);
        } else if (e) {(
            function(){
                var t=document.createElement('doc:rdy');
                try {
                    t.doScroll('left'); i(); t=null;
                } catch(e) {st(arguments.callee,0);}
            })();
        } else window.onload=i;
    },
    imageReady: function(i){
        if ($('image').readyState=='loaded'||$('image').readyState=='complete') {
          i();
        } else
        $('image').onload=i;
    },
    // Common
    debug : function(keys) {
        if (!this.debugMode) return;
        var mes = "";
        for (var i = 0; i < keys.length; i++) mes += this.ERRORS[keys[i]] + " : ";
        mes = mes.substring(0, mes.length - 3);
        alert(mes);
    },
    init : function(hash, node, imagenode) {

        if (typeof node == "undefined") {
            var _this = this;
            this.domReady(
                function() {_this.init(hash, 1)}
            );
            return;
        }
        if (typeof imagenode == "undefined") {
            var _this = this;
            this.imageReady(
                function() {_this.init(hash, node, 1)}
            );
            return;
        }
        this.image = $(this.id);
        if (this.image == null) {
            this.debug([1,2]);
                return;
        }
        if (this.image.nodeName.toLowerCase() != "img") {
            this.debug([1,3]);
                return;
        }
        try {
            for (var i in hash) this[i] = hash[i];
            if (this.onUpdate == null) {
                this.debug([1,4]);
                    return;
            }
            if (!document.body) {
                this.debug([1,5]);
                    return;
            }
            this.image.ondragstart = function() {return false;} // IE fix
            // Set default
            this.redefine();
            //alert(" top:"+this.iTop+" left:"+this.iLeft+" width:"+this.iWidth+" height:"+this.iHeight);
            this.cropTop = this.iTop +this.cropTop;
            this.cropLeft = this.iLeft +this.cropLeft;
            this.iMaxWidth = this.iWidth;
            this.iMaxHeight = this.iHeight;
            this.iMinWidth = this.cropMinWidth;
            this.iMinHeight = this.cropMinHeight;
            this.iRate = this.cropWidth / this.cropHeight;
            if (this.cropWidth==150&&this.cropHeight==150){
              if (this.iHeight>this.iWidth){
              this.cropWidth=this.iWidth;
              this.cropHeight=this.cropWidth;
              } else {
              this.cropHeight=this.iHeight;
              this.cropWidth=this.cropHeight;
              }
            }
            this.drawCropBlock();
            this.drawResizeBlocks();
            // Add handers
            var _this = this;
            this.addMouseHandler(document, "mousemove", function (evt) {
                _this.cropMoveHandler(evt);
                _this.resizeMoveHandler(evt);

            });
            this.addMouseHandler(document, "mouseup", function () {
                _this.cropMoveState = false;
                _this.resizeTRMoveState = false;
                _this.resizeBRMoveState = false;
                _this.resizeTLMoveState = false;
                _this.resizeBLMoveState = false;
                _this.redefine();
            });
            this.addMouseHandler(_this.crop, "mousedown", function (evt) {
                _this.cropMoveState = true;
                evt = evt || window.event;
                if (evt.preventDefault && _this.stopSelection) evt.preventDefault();
                _this.X0 = _this.defPosition(evt).x;
                _this.Y0 = _this.defPosition(evt).y;
            });
            this.addMouseHandler(_this.resizeBR, "mousedown", function (evt) {
                _this.resizeBRMoveState = true;
                evt = evt || window.event;
                if (evt.preventDefault && _this.stopSelection) evt.preventDefault();
                _this.X0 = _this.defPosition(evt).x;
                _this.Y0 = _this.defPosition(evt).y;
                _this.iBuferWidth = _this.cropWidth;
                _this.iBuferHeight = _this.cropHeight;
            });
            this.addMouseHandler(_this.resizeTL, "mousedown", function (evt) {
                _this.resizeTLMoveState = true;
                evt = evt || window.event;
                if (evt.preventDefault && _this.stopSelection) evt.preventDefault();
                _this.X0 = _this.defPosition(evt).x;
                _this.Y0 = _this.defPosition(evt).y;
                _this.iBuferWidth = _this.cropWidth;
                _this.iBuferHeight = _this.cropHeight;
            });
            this.addMouseHandler(_this.resizeBL, "mousedown", function (evt) {
                _this.resizeBLMoveState = true;
                evt = evt || window.event;
                if (evt.preventDefault && _this.stopSelection) evt.preventDefault();
                _this.X0 = _this.defPosition(evt).x;
                _this.Y0 = _this.defPosition(evt).y;
                _this.iBuferWidth = _this.cropWidth;
                _this.iBuferHeight = _this.cropHeight;
            });
            this.addMouseHandler(_this.resizeTR, "mousedown", function (evt) {
                _this.resizeTRMoveState = true;
                evt = evt || window.event;
                if (evt.preventDefault && _this.stopSelection) evt.preventDefault();
                _this.X0 = _this.defPosition(evt).x;
                _this.Y0 = _this.defPosition(evt).y;
                _this.iBuferWidth = _this.cropWidth;
                _this.iBuferHeight = _this.cropHeight;
            });
        } catch(e) {this.debug([1]);}
    },
    redefine : function() {
        this.iTop = this.absPosition(this.image).y;
        this.iLeft = this.absPosition(this.image).x;
		this.iWidth = this.image.width ? parseInt(this.image.width) : this.image.offsetWidth;
		this.iHeight = this.image.height ? parseInt(this.image.height) : this.image.offsetHeight;
        if (this.crop) {
              this.cropLeft = parseInt(this.crop.style.left);
              this.cropTop = parseInt(this.crop.style.top);
        }
        this.objx=this.cropLeft-this.iLeft;
        this.objy=this.cropTop-this.iTop;
        this.onUpdate();
    },
    // Crop
    drawCropBlock : function() {
        if (!$("cropDivId_" + this.id)) {
            this.crop = document.createElement("div");
            this.crop.id = "cropDivId_" + this.id;
            this.crop.style.width = this.cropWidth + "px";
            this.crop.style.height = this.cropHeight + "px";
            this.crop.className = "cropDiv";
            //this.crop.style.display = "none";
            document.body.appendChild(this.crop);
        }
        this.crop = $("cropDivId_" + this.id);
        this.crop.style.top = this.cropTop + "px";
        this.crop.style.left = this.cropLeft + "px";
        if (this.cropBackground) this.crop.style.background = this.cropBackground;
        this.crop.style.display = "";
    },
    cropMoveHandler : function(evt) {
        if (!this.cropMoveState) return;

        evt = evt || window.event;
        //alert(this.defPosition(evt).x+" "+this.X0+" "+this.cropLeft);
        var newX = this.defPosition(evt).x - this.X0 + this.cropLeft;
        var newY = this.defPosition(evt).y - this.Y0 + this.cropTop;
        if (newX < this.iLeft) newX = this.iLeft;
        if (newX + this.cropWidth > this.iLeft + this.iWidth) newX = this.iLeft + this.iWidth - this.cropWidth;
        if (newY < this.iTop) newY = this.iTop;
        if (newY + this.cropHeight > this.iTop + this.iHeight) newY = this.iTop + this.iHeight - this.cropHeight;
        this.crop.style.top = newY + "px";
        this.crop.style.left = newX + "px";
        this.resizeBR.style.top = (parseInt(this.crop.style.top)+parseInt(this.crop.style.height) - 5) + "px"; //resizeTop
        this.resizeBR.style.left = (parseInt(this.crop.style.left)+parseInt(this.crop.style.width) - 5) + "px"; //resizeLeft
        this.resizeTL.style.top = (parseInt(this.crop.style.top)-4) + "px"; //resizeTop
        this.resizeTL.style.left = (parseInt(this.crop.style.left)-4) + "px"; //resizeLeft
        this.resizeBL.style.top = (parseInt(this.crop.style.top)+parseInt(this.crop.style.height)-4) + "px"; //resizeTop
        this.resizeBL.style.left = (parseInt(this.crop.style.left)-4) + "px"; //resizeLeft
        this.resizeTR.style.top = (parseInt(this.crop.style.top)-4) + "px"; //resizeTop
        this.resizeTR.style.left = (parseInt(this.crop.style.left)+parseInt(this.crop.style.width)-5) + "px"; //resizeLeft
        this.objx=newX-this.iLeft;
        this.objy=newY-this.iTop;
        this.onUpdate();
    },
    // Resize
    drawResizeBlocks : function() {
        if (!$("resizeBRDivId_" + this.id)) {
            this.resizeBR = document.createElement("div");
            this.resizeBR.id = "resizeBRDivId_" + this.id;
            this.resizeBR.className = "resizeDivnw";
            this.resizeBR.innerHTML = "";
            this.resizeBR.style.width = this.resizeWidth + "px";
            this.resizeBR.style.height = this.resizeHeight + "px";
            this.resizeBR.style.display = "none";
            document.body.appendChild(this.resizeBR);
        }
        this.resizeBR = $("resizeBRDivId_" + this.id);
        this.resizeBR.style.display = "";
        if (!$("resizeTLDivId_" + this.id)) {
            this.resizeTL = document.createElement("div");
            this.resizeTL.id = "resizeTLDivId_" + this.id;
            this.resizeTL.className = "resizeDivnw";
            this.resizeTL.innerHTML = "";
            this.resizeTL.style.width = this.resizeWidth + "px";
            this.resizeTL.style.height = this.resizeHeight + "px";
            this.resizeTL.style.display = "none";
            document.body.appendChild(this.resizeTL);
        }
        this.resizeTL = $("resizeTLDivId_" + this.id);
        this.resizeTL.style.display = "";
        if (!$("resizeBLDivId_" + this.id)) {
            this.resizeBL = document.createElement("div");
            this.resizeBL.id = "resizeBLDivId_" + this.id;
            this.resizeBL.className = "resizeDives";
            this.resizeBL.innerHTML = "";
            this.resizeBL.style.width = this.resizeWidth + "px";
            this.resizeBL.style.height = this.resizeHeight + "px";
            this.resizeBL.style.display = "none";
            document.body.appendChild(this.resizeBL);
        }
        this.resizeBL = $("resizeBLDivId_" + this.id);
        this.resizeBL.style.display = "";
        if (!$("resizeTRDivId_" + this.id)) {
            this.resizeTR = document.createElement("div");
            this.resizeTR.id = "resizeTRDivId_" + this.id;
            this.resizeTR.className = "resizeDives";
            this.resizeTR.innerHTML = "";
            this.resizeTR.style.width = this.resizeWidth + "px";
            this.resizeTR.style.height = this.resizeHeight + "px";
            this.resizeTR.style.display = "none";
            document.body.appendChild(this.resizeTR);
        }
        this.resizeTR = $("resizeTRDivId_" + this.id);
        this.resizeTR.style.display = "";
        this.setResizeVars();
    },
    setResizeVars : function() {
          this.redefine();
          this.resizeBR.style.top = (parseInt(this.crop.style.top)+parseInt(this.crop.style.height) - 5) + "px"; //resizeTop
          this.resizeBR.style.left = (parseInt(this.crop.style.left)+parseInt(this.crop.style.width) - 5) + "px"; //resizeLeft
          this.resizeTL.style.top = (parseInt(this.crop.style.top)-4) + "px"; //resizeTop
          this.resizeTL.style.left = (parseInt(this.crop.style.left)-4) + "px"; //resizeLeft
          this.resizeBL.style.top = (parseInt(this.crop.style.top)-4+parseInt(this.crop.style.height)) + "px"; //resizeTop
          this.resizeBL.style.left = (parseInt(this.crop.style.left)-4) + "px"; //resizeLeft
          this.resizeTR.style.top = (parseInt(this.crop.style.top)-4) + "px"; //resizeTop
          this.resizeTR.style.left = (parseInt(this.crop.style.left)+parseInt(this.crop.style.width) - 5) + "px"; //resizeLeft
    },
    resizeMoveHandler : function(evt) {
        evt = evt || window.event;
        var hW, hH,hLeft,hTop;
        if (!this.resizeBRMoveState&&!this.resizeTLMoveState&&!this.resizeBLMoveState&&!this.resizeTRMoveState) return;
        var defX=this.defPosition(evt).x;
        var defY=this.defPosition(evt).y;

        if (this.resizeTRMoveState){
            hW = this.iBuferWidth + defX - this.X0;
            hH = this.iBuferHeight + defY - this.Y0;
            this.cropWidth=hW;
            this.cropHeight=(this.saveProportions ? hW / this.iRate : hH);
        } else if (this.resizeBRMoveState){
            hW = this.iBuferWidth + defX - this.X0;
            hH = this.iBuferHeight + defY - this.Y0;
            this.cropWidth=hW;
            this.cropHeight=(this.saveProportions ? hW / this.iRate : hH);
        } else if (this.resizeTLMoveState){
            hW = this.iBuferWidth - defX + this.X0;
            hH = this.iBuferHeight - defY + this.Y0;
            this.cropWidth=hW;
            this.cropHeight=(this.saveProportions ? hW / this.iRate : hH);
        } else if (this.resizeBLMoveState){
            hW = this.iBuferWidth - defX + this.X0;
            hH = this.iBuferHeight + defY - this.Y0;
            this.cropWidth=hW;
            this.cropHeight=(this.saveProportions ? hW / this.iRate : hH);
        }
        if (this.cropWidth<this.cropMinWidth||this.cropHeight<this.cropMinHeight) {
          this.cropWidth=this.cropMinWidth;
          this.cropHeight=this.cropWidth;
        }
        if (this.cropWidth>this.iMaxWidth||this.cropHeight>this.iMaxHeight) {
          this.cropWidth=this.iMaxWidth;
          this.cropHeight=this.cropWidth;
        }


        if (hW <= this.iMinWidth) hW = this.iMinWidth;
        if (hW >= this.iMaxWidth) hW = this.iMaxWidth;
        if (hH <= this.iMinHeight) hH = this.iMinHeight;
        if (hH >= this.iMaxHeight) hH = this.iMaxHeight;

        if (this.resizeTLMoveState){
           if (this.iTop<=this.cropTop&&this.cropLeft>=this.iLeft){
              this.cropTop = this.cropTop-this.cropHeight+parseInt(this.crop.style.height);
           }
           if (this.iTop>this.cropTop){
              this.cropTop = this.iTop;
           }
           if (this.cropLeft>=this.iLeft&&this.iTop<this.cropTop)
              this.cropLeft=this.cropLeft-this.cropWidth+parseInt(this.crop.style.width);

           if (this.cropLeft<this.iLeft||this.iTop>=this.cropTop){
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
              if (this.cropLeft<this.iLeft)
                this.cropLeft=this.iLeft;
              if (this.cropTop<this.iTop)
                this.cropTop = this.iTop;
           }
        }

        if (this.resizeTRMoveState){
           if (this.iTop<=this.cropTop&&this.cropLeft+this.cropWidth<=this.iLeft+this.iWidth){
              this.cropTop = this.cropTop-this.cropHeight+parseInt(this.crop.style.height);
           }
           if (this.iTop>=this.cropTop){
              this.cropTop = this.iTop;
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
           }

           if (this.cropLeft<this.iLeft||this.iTop>=this.cropTop){
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
              if (this.cropLeft<this.iLeft)
                this.cropLeft=this.iLeft;
              if (this.cropTop<this.iTop)
                this.cropTop = this.iTop;
           }
           if (this.iLeft+this.iWidth<this.cropLeft+this.cropWidth){
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
           }
        }

        if (this.resizeBLMoveState){
           if (this.iTop+this.iHeight<this.cropTop+this.cropHeight){
              this.cropHeight=parseInt(this.crop.style.height);
              this.cropWidth=(this.saveProportions ? this.cropHeight / this.iRate : this.cropHeight);
           }
           if (this.cropLeft>=this.iLeft)
           this.cropLeft=this.cropLeft-this.cropWidth+parseInt(this.crop.style.width);
           if (this.cropLeft<this.iLeft){
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
              this.cropLeft=this.iLeft;
           }
        }

        if (this.resizeBRMoveState){
           if (this.iTop+this.iHeight<this.cropTop+this.cropHeight){
              this.cropHeight=parseInt(this.crop.style.height);
              this.cropWidth=(this.saveProportions ? this.cropHeight / this.iRate : this.cropHeight);
           }
           if (this.iLeft+this.iWidth<this.cropLeft+this.cropWidth){
              this.cropWidth=parseInt(this.crop.style.width);
              this.cropHeight=(this.saveProportions ? this.cropWidth / this.iRate : this.cropWidth);
           }
        }


		this.crop.style.width = this.cropWidth + "px";
		this.crop.style.height = this.cropHeight + "px";
        this.crop.style.left = this.cropLeft +"px";
        this.crop.style.top = this.cropTop +"px";

        this.setResizeVars();
    }
}

var cleverdatepicker = { // NAMESPACE
    process : function(id,elemid) {
        return new this.construct(id,elemid);
    }
};

cleverdatepicker.construct = function(id,elemid) { // Constructor
    this.id = id;
    this.elemid = elemid;
    this.dateblock = null;
    this.onUpdate = null;
    this.date = null;
    this.days = ["Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"];
    this.monthes = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"];
    this.monthes2 = ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];
    this.curday=1;
    this.curmonth=1;
    this.curyear=2011;
    this.setday=1;
    this.setmonth=1;
    this.setyear=2011;
    this.table = null;
}

cleverdatepicker.construct.prototype = {
    addMouseHandler : function(object, event, handler, useCapture) {
        if (object.addEventListener) {
            object.addEventListener(event, handler, useCapture ? useCapture : false);
        } else if (object.attachEvent) {
            object.attachEvent('on' + event, handler);
        } else alert("Нельзя навесить события");
    },
    MousePosition : function(event) {
        var x = y = 0;
        if (document.attachEvent != null) {
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
        }
        if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }
        return {x:x, y:y};
    },
    getSource : function (evt){
        var elem=null;
        if (window.event) {
            evt = window.event; // For IE
            return evt.srcElement;
        } else {
            return evt.target; // For Firefox
        }

    },
    ElemPosition : function(obj) {
        var x = y = 0;
        while(obj.offsetParent) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return {x:x, y:y};
    },
    daysInMonth : function (iMonth, iYear) {
        return 32 - new Date(iYear, iMonth, 32).getDate();
    },
    firstDayInWeek : function (iMonth, iYear){
        var day=new Date(iYear, iMonth, 1).getDay();
        if (day<=0) day=7+day;
        return day-1;
    },
    createCalendar : function (_this){
                if (_this.table!=null&&_this.dateblock!=null){
                    _this.dateblock.removeChild(_this.table);
                    _this.table=null;
                }
                _this.table = document.createElement("TABLE");
                _this.table.style.width="100%";
                _this.table.className="table";
                _this.dateblock.appendChild(_this.table);
                var rowHeader = _this.table.insertRow(-1);
                rowHeader.className="tableheader bgcolor";
                var cellml = rowHeader.insertCell(-1);
                cellml.style.cursor="pointer";
                cellml.innerHTML="&laquo;";
                        _this.addMouseHandler(cellml, "mousedown", function (evt) {
                            _this.curday=1;
                            _this.curyear--;
                            _this.createCalendar(_this);
                            return false;
                        });
                var cellml = rowHeader.insertCell(-1);
                cellml.style.cursor="pointer";
                cellml.innerHTML="&lt;";
                        _this.addMouseHandler(cellml, "mousedown", function (evt) {
                            _this.curday=1;
                            _this.curmonth--;
                            if (_this.curmonth<1) {_this.curmonth=12; _this.curyear--; }
                            _this.createCalendar(_this);
                            return false;
                        });

                var cell = rowHeader.insertCell(-1);
                cell.innerHTML=_this.monthes[_this.curmonth-1]+" "+_this.curyear;
                cell.style.textAlign="center";
                cell.id="datetxt";
                cell.style.verticalAlign="middle";
                cell.colSpan=3;
                var cellmg = rowHeader.insertCell(-1);
                cellmg.style.cursor="pointer";
                cellmg.innerHTML="&gt;";
                        _this.addMouseHandler(cellmg, "mousedown", function (evt) {
                            _this.curday=1;
                            _this.curmonth++;
                            if (_this.curmonth>12) {_this.curmonth=1; _this.curyear++; }
                            _this.createCalendar(_this);
                            return false;
                        });
                var cellmg = rowHeader.insertCell(-1);
                cellmg.style.cursor="pointer";
                cellmg.innerHTML="&raquo;";
                        _this.addMouseHandler(cellmg, "mousedown", function (evt) {
                            _this.curday=1;
                            _this.curyear++;
                            _this.createCalendar(_this);
                            return false;
                        });
                var row = _this.table.insertRow(-1);
                for (var i=1; i<=7; i++){
                  var cell = row.insertCell(-1);
                  cell.className="days";
                  cell.innerHTML=_this.days[i-1];
                }
                var num=1;
                var r=0;
                while(num<=_this.daysInMonth(_this.curmonth-1,_this.curyear)){
                  r++;

                  var row = _this.table.insertRow(-1);
                  for (var d=0; d<7; d++){
                    var cell = row.insertCell(-1);
                    if ((r>1&&num<=_this.daysInMonth(_this.curmonth-1,_this.curyear))||(r==1&&d>=_this.firstDayInWeek(_this.curmonth-1,_this.curyear))){


                        cell.innerHTML=num;
                        cell.style.cursor="pointer";
                        if (num==_this.setday&&_this.curyear==_this.setyear&&_this.curmonth==_this.setmonth) cell.className="bgcolor currentDay";
                        cell.id=num;
                        num++;
                        _this.addMouseHandler(cell, "mousedown", function (evt) {
                            var elem=null;
                            if (window.event) {
                                evt = window.event; // For IE
                                elem = evt.srcElement;
                            } else {
                                elem = evt.target; // For Firefox
                            }

                            $(_this.elemid).value=_this.format(elem.id)+"."+_this.format(_this.curmonth)+"."+_this.curyear;
                            if ($(_this.elemid+"_hidden"))
                                $(_this.elemid+"_hidden").value=_this.format(elem.id)+"."+_this.format(_this.curmonth)+"."+_this.curyear;
                            document.body.removeChild(_this.dateblock);
                            _this.dateblock=null;
                            _this.table=null;
                            return false;
                        });
                        _this.addMouseHandler(cell, "mouseover", function (evt) {
                            var elem=null;
                            if (window.event) {
                                evt = window.event; // For IE
                                elem = evt.srcElement;
                            } else {
                                elem = evt.target; // For Firefox
                            }

                            elem.className="over";
                            return false;
                        });
                        _this.addMouseHandler(cell, "mouseout", function (evt) {
                            var elem=null;
                            if (window.event) {
                                evt = window.event; // For IE
                                elem = evt.srcElement;
                            } else {
                                elem = evt.target; // For Firefox
                            }
                            if (elem.id==_this.setday&&_this.curyear==_this.setyear&&_this.curmonth==_this.setmonth) elem.className="bgcolor currentDay";
                            else
                            elem.className="days";
                            return false;
                        });


                    }
                  }
                }
                var rowFooter = _this.table.insertRow(-1);
                rowFooter.className="bgcolor";
                var cellft = rowFooter.insertCell(-1);
                cellft.colSpan=7;
                cellft.innerHTML="Выбранная дата: "+_this.setday+" "+_this.monthes2[_this.setmonth-1]+" "+_this.setyear;
                cellft.style.padding="2px 0px 2px 0px";

    },
    format: function (int){
      if (parseInt(int)<10) return "0"+parseInt(int);
      else return parseInt(int);
    },
    frm: function (int){
      if (int.substr(0,1)==0) int=int.substr(1,int.length);
      return int;
    },
    init : function(hash) {
            for (var i in hash) this[i] = hash[i];
            var _this = this;
            this.addMouseHandler(document, "mousedown", function (evt) {
                if (_this.dateblock){
                  var blockcalendar = false;
                  var elem=_this.getSource(evt);
                  //alert(elem.className);
                  while (elem.parentNode){
                    // alert(elem.className);
                    if (elem.className=='tableheader bgcolor'||elem.className=='table') blockcalendar=true;
                    elem = elem.parentNode;
                  }
                  if (!blockcalendar){
                    document.body.removeChild(_this.dateblock);
                    _this.dateblock=null;
                            _this.table=null;
                  }
                }

                return false;
            });
            this.addMouseHandler($(this.id), "mouseup", function () {
                _this.date = $(_this.elemid).value;
                _this.dateblock=document.createElement("DIV");
                _this.dateblock.style.position = "absolute";
                _this.dateblock.style.top = _this.ElemPosition($(_this.elemid)).y+parseInt($(_this.elemid).offsetHeight)+"px";
                _this.dateblock.style.left = _this.ElemPosition($(_this.elemid)).x+"px";
                _this.dateblock.className = "calendarblock";
                var curdtarr=_this.date.split('.');
                _this.curday=_this.frm(curdtarr[0]);
                _this.curmonth=_this.frm(curdtarr[1]);
                _this.curyear=_this.frm(curdtarr[2]);
                _this.setday=_this.frm(curdtarr[0]);
                _this.setmonth=_this.frm(curdtarr[1]);
                _this.setyear=_this.frm(curdtarr[2]);
                document.body.appendChild(_this.dateblock);
                _this.createCalendar(_this);
            });



    }
}


var cleverdrop = { // NAMESPACE
    process : function(id) {
        return new this.construct(id);
    }
};

cleverdrop.construct = function(id) { // Constructor
    this.id = id;
    this.container = null;
    this.dragelem = null;
    this.waslast = false;
    this.startX = 0;
    this.startY = 0;
    this.mouseX = 0;
    this.mouseY = 0;
    this.tmpli = null;
    this.droparea = null;
    this.movingleft = false;
    this.dragging = false;
    this.type = 'items';
    this.onUpdate = null;
    this.newId=0;
    this.oldId=0;
    this.currentId=0;
    this.dragwidth=0;
    this.dragheight=0;
}

cleverdrop.construct.prototype = {
    addMouseHandler : function(object, event, handler, useCapture) {
        if (object.addEventListener) {
            object.addEventListener(event, handler, useCapture ? useCapture : false);
        } else if (object.attachEvent) {
            object.attachEvent('on' + event, handler);
        } else alert("Нельзя навесить события");
    },
    MousePosition : function(event) {
        var x = y = 0;
        if (document.attachEvent != null) {
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
        }
        if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }
        return {x:x, y:y};
    },
    ElemPosition : function(obj) {
        var x = y = 0;
        while(obj.offsetParent) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return {x:x, y:y};
    },
    getSource : function (evt){
        var elem=null;
        if (window.event) {
            evt = window.event; // For IE
            return evt.srcElement;
        } else {
            return evt.target; // For Firefox
        }

    },
    sort : function() {
            var smaller=this.oldId;
            var bigger =this.newId;
            var down=true;
            var middle=0;
            if (bigger<smaller) {
                middle=smaller;
                smaller=bigger;
                bigger=middle;
                down=false;
            }
            var tags=this.container.getElementsByTagName('LI');
            var currid=0;
            for (i=0; i<tags.length; i++){
              currid = parseInt(tags[i].getAttribute('order'));
              if ((currid>=smaller)&&(currid<=bigger)){
                if (currid!=this.oldId){
                  if (down)
                        tags[i].setAttribute('order',currid-1);
                  else
                        tags[i].setAttribute('order',currid+1);
                } else tags[i].setAttribute('order',this.newId);
              }
            }
    },
    getParentLi : function(obj,thisid){
      while (obj.parentNode.id!=thisid&&obj.tagName!='LI')
        obj=obj.parentNode;
      return obj;
    },

  	nextItem : function(item, tagName) {
  		if (item == null) return
  		var next = item.nextSibling
  		while (next != null) {
  			if (next.tagName == tagName) return next
  			next = next.nextSibling
  		}
  		return null
  	},

  	previousItem : function(item, tagName) {
  		var previous = item.previousSibling
  		while (previous != null) {
  			if (previous.tagName == tagName) return previous
  			previous = previous.previousSibling
  		}
  		return null
  	},

  	moveBefore : function(item1, item2) {
  	    //alert(item1.tagName);
        if (item1.parentNode!=null){
  	     	var parent = item1.parentNode
    		parent.removeChild(item1)
    		parent.insertBefore(item1, item2)

        }
  	},

  	moveAfter : function(item1, item2) {
        if (item1.parentNode!=null){
  	     	var parent = item1.parentNode
    		parent.removeChild(item1)
    		parent.insertBefore(item1, item2.nextSibling)
        }
  	},


    init : function(hash) {
            for (var i in hash) this[i] = hash[i];
            this.container = $(this.id);
            this.container.className="container"+this.type;
            var _this = this;
            this.addMouseHandler(document, "mousemove", function (evt) {
              if (_this.dragelem==null) return true;
              if (_this.dragging==false) return true;
              var mx=_this.MousePosition(evt).x;
              var my=_this.MousePosition(evt).y;
              _this.dragelem.style.left = mx+10+"px";
              _this.dragelem.style.top = my+10+"px";
              var dragarea = _this.getSource(evt);
              while(dragarea.parentNode!=null&&dragarea.tagName!='LI'&&dragarea.parentNode.id!=_this.id) dragarea = dragarea.parentNode;
              if (_this.tmpli.parentNode==null || dragarea==_this.tmpli || dragarea.tagName != 'LI' || dragarea.tagName != 'LI' || dragarea.parentNode.id!=_this.tmpli.parentNode.id) return true;


              if (my <= _this.ElemPosition(dragarea).y+dragarea.offsetHeight && mx <= _this.ElemPosition(dragarea).x+dragarea.offsetWidth)
         	  _this.moveBefore(_this.tmpli, dragarea)

              if (_this.ElemPosition(dragarea).y <= my && _this.ElemPosition(dragarea).x <= mx)
         	  _this.moveAfter(_this.tmpli, dragarea)
              return true;

            });
            this.addMouseHandler(document, "mouseup", function () {
                  if (_this.dragelem==null) return true;
                  if (_this.dragging==false) return true;
                  _this.dragging = false;
                  var timer=setInterval(function(){
                  _this.dragelem.style.left=(parseInt(_this.dragelem.style.left)+_this.ElemPosition(_this.tmpli).x)/2+"px";
                  _this.dragelem.style.top=(parseInt(_this.dragelem.style.top)+_this.ElemPosition(_this.tmpli).y)/2+"px";
                  if (  (Math.abs(_this.ElemPosition(_this.dragelem).x-_this.ElemPosition(_this.tmpli).x)<5) && (Math.abs(_this.ElemPosition(_this.dragelem).y-_this.ElemPosition(_this.tmpli).y)<5)  ){
                    _this.currentId=_this.dragelem.getAttribute('elemid');
                    var notchange=false;
                    if (_this.tmpli.style.left==_this.startX&&_this.tmpli.style.top==_this.startX) notchange=true;
                    _this.dragelem.style.position="";
                    _this.container.insertBefore(_this.dragelem,_this.tmpli);
                    _this.dragelem.className="";
                    _this.dragelem.style.zIndex=0;
                    _this.dragelem.style.left=_this.startX;
                    _this.dragelem.style.top=_this.startY;
                    _this.dragelem.style.width = _this.dragwidth+"px";
                    _this.dragelem.style.height = _this.dragheight+"px";

                    _this.container.removeChild(_this.tmpli);

                    var lastchild=_this.container.lastChild;
                    if (lastchild.tagName==undefined) lastchild=lastchild.previousSibling;
                    if (!(_this.dragelem == lastchild && _this.waslast)){
                		var next = _this.nextItem(_this.dragelem, _this.dragelem.tagName)
                        if (next!=null){
                          if (_this.oldId>parseInt(next.getAttribute("order")))
                            _this.newId=parseInt(next.getAttribute("order"));
                          else
                            _this.newId=parseInt(next.getAttribute("order"))-1;
                        } else {
                	      var prev = _this.previousItem(_this.dragelem, _this.dragelem.tagName);
                          if (prev)
                              _this.newId=parseInt(prev.getAttribute("order"));
                        }
                    }
                    //alert(_this.newId+" "+_this.oldId);
                    clearInterval(timer);
                    if (!(_this.dragelem == lastchild && _this.waslast))
                        _this.sort();
                    _this.dragelem = null;
                    _this.droparea = null;
                    _this.tmpli = null;
                    _this.onUpdate();
                  }
                },50);
                return false;
            });


            var tags=this.container.getElementsByTagName('A');
            for (i=0; i<tags.length; i++){
              if (tags[i].className=='move'){

                this.addMouseHandler(tags[i], "mousedown", function (evt) {
                    if (_this.dragging) return true;
                    if (evt.preventDefault) evt.preventDefault();
                    _this.dragging = true;
                    _this.dragelem=_this.getParentLi(_this.getSource(evt),_this.id);
                    if (_this.dragelem.parentNode.id!=_this.id){_this.dragging=false; return true};
                    _this.waslast=false;
                    var lastchild=_this.container.lastChild;
                    if (lastchild.tagName==undefined) lastchild=lastchild.previousSibling;
                    if (_this.dragelem == lastchild) _this.waslast=true;
                    _this.startX=_this.dragelem.style.left;
                    _this.startY=_this.dragelem.style.top;
                    _this.dragwidth = parseInt(_this.dragelem.offsetWidth);
                    _this.dragheight = parseInt(_this.dragelem.offsetHeight);
                    _this.mouseX=_this.MousePosition(evt).x;
                    _this.mouseY=_this.MousePosition(evt).y;
                    _this.tmpli = document.createElement('LI');
                    _this.tmpli.className = "tmp";

                    var pclass=_this.getSource(evt).parentNode.className;
                    if (pclass=='editpanelbig'){
                        if (IE){
                        _this.tmpli.style.width=_this.dragwidth-2+"px";
                        _this.tmpli.style.height=_this.dragheight+20+"px";
                        }
                        if (NS||OP){
                        _this.tmpli.style.width=_this.dragwidth-12+"px";
                        _this.tmpli.style.height=_this.dragheight+18+"px";
                        }
                    } else
                    if (pclass=='editpanelbig2')
                    {
                        if (IE){
                        _this.tmpli.style.width=_this.dragwidth-2+"px";
                        _this.tmpli.style.height=_this.dragheight+"px";
                        }
                        if (NS||OP){
                        _this.tmpli.style.width=_this.dragwidth-12+"px";
                        _this.tmpli.style.height=_this.dragheight-2+"px";
                        }
                    } else {
                        if (IE){
                        _this.tmpli.style.width=_this.dragwidth+"px";
                        _this.tmpli.style.height=_this.dragheight+"px";
                        }
                        if (NS||OP){
                        _this.tmpli.style.width=_this.dragwidth-2+"px";
                        _this.tmpli.style.height=_this.dragheight-2+"px";
                        }
                    }

                    var tmpleft=_this.dragelem.offsetLeft;
                    var tmptop=_this.dragelem.offsetTop;
                    _this.container.insertBefore(_this.tmpli,_this.dragelem);  //appendChild(_this.tmpli);
                    _this.tmpli.setAttribute('order',parseInt(_this.dragelem.getAttribute('order')));
                    _this.dragelem.className = "dragged";
                    _this.dragelem.style.position="absolute";
                    _this.dragelem.style.left=_this.MousePosition(evt).x+10+"px";
                    _this.dragelem.style.top=_this.MousePosition(evt).y+10+"px";
                    _this.dragelem.style.width = _this.dragwidth+"px";
                    _this.dragelem.style.height = _this.dragheight+"px";
                    _this.dragelem.style.zIndex=10001;
                    _this.oldId=parseInt(_this.dragelem.getAttribute('order'));
                    _this.newId=parseInt(_this.dragelem.getAttribute('order'));
                    _this.currentId=parseInt(_this.dragelem.getAttribute('elemid'));
                    return true;
                }
                );
              }
            }
    }
}


var cleverhint = { // NAMESPACE
    process : function() {
        return new this.construct();
    }
};

cleverhint.construct = function() { // Constructor
}

cleverhint.construct.prototype = {
    addMouseHandler : function(object, event, handler, useCapture) {
        if (object.addEventListener) {
            object.addEventListener(event, handler, useCapture ? useCapture : false);
        } else if (object.attachEvent) {
            object.attachEvent('on' + event, handler);
        } else alert("Нельзя навесить события");
    },
    MousePosition : function(event) {
        var x = y = 0;
        if (document.attachEvent != null) {
            x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
        }
        if (!document.attachEvent && document.addEventListener) { // Gecko
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }
        return {x:x, y:y};
    },
    getSource : function (evt){
        var elem=null;
        if (window.event) {
            evt = window.event; // For IE
            return evt.srcElement;
        } else {
            return evt.target; // For Firefox
        }

    },
    ElemPosition : function(obj) {
        var x = y = 0;
        while(obj.offsetParent) {
            x += obj.offsetLeft;
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return {x:x, y:y};
    },
    init : function() {
            var _this = this;
            var tags = document.getElementsByTagName("*");
            for (var i in tags){
              //alert(tags[i].getAttribute('clhint'));
              if ((tags[i].tagName=='A'||tags[i].tagName=='IMG')&&tags[i].getAttribute('clhint')&&tags[i].getAttribute('clhint')!=null){
                this.addMouseHandler(tags[i], "mousemove", function (evt) {
                  var _thistag=_this.getSource(evt);
                  if (!$("hintwin")) return;
                    $("hintwin").innerHTML=_thistag.getAttribute('clhint');
                    if (parseInt($("hintwin").offsetWidth)>200){ $("hintwin").style.width="200px";}
                    $("hintwin").style.left=parseInt(_this.MousePosition(evt).x)+10+"px";
                    $("hintwin").style.top=parseInt(_this.MousePosition(evt).y)+10+"px";
                });
                this.addMouseHandler(tags[i], "mouseover", function (evt) {
                  var _thistag=_this.getSource(evt);
                  var id=parseInt(Math.random()*10000000);
                  _thistag.setAttribute('clhint_id',id);
                  var div = document.createElement("DIV");
                  div.id="hintwin";
                  div.className="hint";
                  div.style.position="absolute";
                  div.innerHTML=_thistag.getAttribute('clhint');
                  document.body.appendChild(div);
                  if (parseInt(div.offsetWidth)>200){ div.style.width="200px";}
                  if (parseInt($("hintwin")).offsetWidth>200){ $("hintwin").style.width="200px";}
                  $("hintwin").style.left=parseInt(_this.MousePosition(evt).x)+10+"px";
                  $("hintwin").style.top=parseInt(_this.MousePosition(evt).y)+10+"px";
                });
                this.addMouseHandler(tags[i], "mouseout", function (evt) {
                  var _thistag=_this.getSource(evt);
                  if ($("hintwin"))
                  document.body.removeChild($("hintwin"));
                });
              }
            }



    }
}


function $(id) {return document.getElementById(id);}

function fconfirm(str){
  if (confirm(str)) {
	return true;
	}
  else {
	return false;
  }
}

function get_basket_count() {
        var count=0;
        if (document.cookie && document.cookie != '') {
                var split = document.cookie.split(';');
                for (var i = 0; i < split.length; i++) {
                        var name_value = split[i].split("=");
                        name_value[0] = name_value[0].replace(/^ /, '');
                        name_value[0]=decodeURIComponent(name_value[0]);
                        if (name_value[0].substring(0,6)=="basket"){
                            name_value[1]=decodeURIComponent(name_value[1]);
                            count += parseInt(name_value[1]);
                        }
                }
        }
        return count;
}
function createCookie(name,value,days) {
        if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+escape(value)+expires+"; path=/";
}
function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
        }
        return null;
}

function isValidEmail (email)
{
 var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
 return template.test(email);
}

function delFromBasket(id){
    if (fconfirm('Вы действительно хотите удалить товар из корзины?')){
    createCookie("basket["+id+"]",0,-1);
    if( $('basketrow'+id) )
    $('basketrow'+id).parentNode.removeChild($('basketrow'+id));
    }
    if ($('basketcount'))
        $('basketcount').innerHTML=get_basket_count();
    if (get_basket_count()==0){
        if ($('nostuffinbasket')) $('nostuffinbasket').style.display="block";
        if ($('formforbasket')) $('formforbasket').style.display="none";

    }
}

function addToBasket(id,count){
    if (isNaN(count)||count==undefined){
    var count=parseInt(readCookie("basket["+id+"]"))+1;
    if (isNaN(count)) count=1;
    }

    createCookie("basket["+id+"]",count);
    if ($('basketcount'))
        $('basketcount').innerHTML=get_basket_count();
    if ($('addtobasket'+id))
        $('addtobasket'+id).innerHTML="Товар в корзине";
    if ($('finalprice'+id))
        $('finalprice'+id).innerHTML=parseInt($('exactprice'+id).value)*count;
}

var marray=Array();
function checkcount(name,label,messageblock,count,mincount){
	if (!$(messageblock)) return;
	var value="";
	if ($(name).tagName=='TEXTAREA') value=$(name).value;
	if ($(name).tagName=='INPUT') value=$(name).value;
	if (value.length>count){
	  marray[name]="Вы превысили максимальное количество для поля "+label+" на "+(value.length-count)+".";
	} else if (mincount!=undefined&&value.length<mincount)
	{
	  marray[name]="Поле "+label+" не может быть менее "+(mincount)+" символов.";
	} else
	{
	  marray[name]="";
	}

	var icount=0;
	var message="";
	for (var str in marray){
		if (marray[str]!=""){
		message=message+marray[str]+"<br>";
		icount++;
		}
	}
	if (icount>0){
		$(messageblock).innerHTML=message;
		$(messageblock).style.display="block";
	} else {
		$(messageblock).innerHTML="";
		$(messageblock).style.display="none";
	}
}

function filter_input(e,regexp)
{
  e=e || window.event;
  var target=e.target || e.srcElement;
  var isIE=document.all;

  if (target.tagName.toUpperCase()=='INPUT')
  {
    var code=isIE ? e.keyCode : e.which;
    if (code<32 || e.ctrlKey || e.altKey) return true;

    var char=String.fromCharCode(code);
    if (!regexp.test(char)) return false;
  }
  return true;
}

var seoclosed=true;
var supportclosed=true;

function getseoparams(message){
    if ($('seotitle')&&message.title!=undefined) {
      $('seotitle').value=message.title;
    } else
      $('seotitle').value=document.title;
    if ($('seokeywords')&&message.keywords!=undefined) $('seokeywords').value=message.keywords;
    if ($('seodescription')&&message.description!=undefined) $('seodescription').value=message.description;
    if ($("supportpanel")) supportclose();
    slideopen();
}


function slideopen(){
    var slidetimer=setInterval(function(){
        $("seopanel").style.display="block";
        var height=parseInt($('seopanel').style.height);
        $('seopanel').setAttribute('style','opacity:'+(height*100/parseInt($('innerseopanel').offsetHeight))/100+';');
        if ($('seopanel').style.setAttribute) $('seopanel').style.setAttribute("filter", "alpha(opacity="+(height*100/parseInt($('innerseopanel').offsetHeight))+");");
        $('seopanel').style.height = height+parseInt((parseInt($('innerseopanel').offsetHeight)-height+10)/5) + "px";
        $('seopanel').style.overflow="hidden";
        if (parseInt($('seopanel').style.height)>=parseInt($('innerseopanel').offsetHeight)-5){
            $('seopanel').style.height = $('innerseopanel').offsetHeight;
            seoclosed=false;
    	    $("aseopanel").setAttribute('style','opacity:1;');
    	    $("aseopanel").setAttribute("filter", "alpha(opacity=100);");
            clearInterval(slidetimer);
        }
    },20);
}
function slideclose(){
    var slidetimer=setInterval(function(){
        var height=parseInt($('seopanel').style.height);
        $('seopanel').setAttribute('style','opacity:'+(height*100/parseInt($('innerseopanel').offsetHeight))/100+';');
        if ($('seopanel').style.setAttribute) $('seopanel').style.setAttribute("filter", "alpha(opacity="+(height*100/parseInt($('innerseopanel').offsetHeight))+");");
        $('seopanel').style.height = (height-height/5) + "px";
        $('seopanel').style.overflow="hidden";

        if (parseInt($('seopanel').style.height)<=5){
            document.body.removeChild($('seopanel'));
            seoclosed=true;
            clearInterval(slidetimer);

        }
    },20);
}

function supportopen(){
    var slidetimer=setInterval(function(){
        $("supportpanel").style.display="block";
        var height=parseInt($('supportpanel').style.height);
        $('supportpanel').setAttribute('style','opacity:'+(height*100/parseInt($('innersupportpanel').offsetHeight))/100+';');
        if ($('supportpanel').style.setAttribute) $('supportpanel').style.setAttribute("filter", "alpha(opacity="+(height*100/parseInt($('innersupportpanel').offsetHeight))+");");
        $('supportpanel').style.height = height+parseInt((parseInt($('innersupportpanel').offsetHeight)-height+10)/5) + "px";
        $('supportpanel').style.overflow="hidden";
        if (parseInt($('supportpanel').style.height)>=parseInt($('innersupportpanel').offsetHeight)-5){
            $('supportpanel').style.height = $('innersupportpanel').offsetHeight;
            supportclosed=false;
    	    $("asupportpanel").setAttribute('style','opacity:1;');
    	    $("asupportpanel").setAttribute("filter", "alpha(opacity=100);");
            clearInterval(slidetimer);
        }
    },20);
}
function supportclose(){
    var slidetimer=setInterval(function(){
        var height=parseInt($('supportpanel').style.height);
        $('supportpanel').setAttribute('style','opacity:'+(height*100/parseInt($('innersupportpanel').offsetHeight))/100+';');
        if ($('supportpanel').style.setAttribute) $('supportpanel').style.setAttribute("filter", "alpha(opacity="+(height*100/parseInt($('innersupportpanel').offsetHeight))+");");
        $('supportpanel').style.height = (height-height/5) + "px";
        $('supportpanel').style.overflow="hidden";

        if (parseInt($('supportpanel').style.height)<=5){
            document.body.removeChild($('supportpanel'));
            supportclosed=true;
            clearInterval(slidetimer);

        }
    },20);
}


function createseo(module,cats_id,elems_id){
  if (!$('seopanel')){

  $("aseopanel").setAttribute('style','opacity:0.6;');
  if ($("aseopanel").style.setAttribute) $("aseopanel").style.setAttribute("filter", "alpha(opacity=60);");

  var seo = document.createElement("DIV");
  var tmp = document.createElement("DIV");
  var form = document.createElement("FORM");
  cat_id=null;
  elem_id=null;
  if (cats_id=='') cats_id=null;
  if (elems_id=='') elems_id=null;
  if (module=='article'){
    elem_id=elems_id;
    cat_id=null;
  }
  if (module=='news'&&cats_id=='year'){
    elem_id=null;
    cat_id=elems_id;
  } else
  if (module=='news'){
    elem_id=elems_id;
    cat_id=null;
  }
  if (module=='gallery'){
    elem_id=null;
    cat_id=elems_id;
  }
  if (module=='products'&&cats_id=='view'){
    elem_id=null;
    cat_id=elems_id;
  } else
  if (module=='products'&&cats_id=='viewelem'){
    elem_id=elems_id;
    cat_id=null;
  }
  var result = document.createElement("DIV");
  result.innerHTML = "&nbsp;";
  result.id="seoresult";
  var title_alt = document.createElement("DIV");
  title_alt.innerHTML = "Заголовок";
  title_alt.style.fontSize="12px";
  title_alt.style.fontWeight="bold";
  title_alt.style.paddingBottom="5px";
  title_alt.style.color="#323232";
  var title = document.createElement("INPUT");
  title.name="title";
  title.style.width="400px";
  title.style.marginBottom="10px";
  title.id="seotitle";
  var clear_title = document.createElement("INPUT");
  clear_title.type="checkbox";
  clear_title.id="crear_seo_title";
  clear_title.onclick=function(){if (this.checked) title.setAttribute("disabled","disabled"); else title.removeAttribute("disabled"); }
  var clear_title_alt = document.createElement("SPAN");
  clear_title_alt.innerHTML="По умолчанию";
  var keywords_alt = document.createElement("DIV");
  keywords_alt.innerHTML = "Ключевые слова";
  keywords_alt.style.fontSize="12px";
  keywords_alt.style.fontWeight="bold";
  keywords_alt.style.paddingBottom="5px";
  keywords_alt.style.color="#323232";
  var keywords = document.createElement("TEXTAREA");
  keywords.name="keywords";
  keywords.style.width="400px";
  keywords.style.height="100px";
  keywords.style.marginBottom="10px";
  keywords.id="seokeywords";
  var description_alt = document.createElement("DIV");
  description_alt.innerHTML = "Описание";
  description_alt.style.fontSize="12px";
  description_alt.style.fontWeight="bold";
  description_alt.style.paddingBottom="5px";
  description_alt.style.color="#323232";
  var description = document.createElement("TEXTAREA");
  description.name="description";
  description.style.width="400px";
  description.style.height="100px";
  description.style.marginBottom="10px";
  description.id="seodescription";
  var submit_div = document.createElement("DIV");
  var submit = document.createElement("INPUT");
  submit.type="submit";
  submit.value="Сохранить";
  submit.onclick=function(){
    if ($('seotitle').getAttribute("disabled"))
        var title="";
    else
        var title=$('seotitle').value;
    ajax("/seo/set/"+module+"/"+elem_id+"/"+cat_id, "seoresult", "title="+title+"&keywords="+$('seokeywords').value+"&description="+$('seodescription').value);
    return false;
  }
  submit_div.appendChild(submit);
  tmp.appendChild(result);
  tmp.appendChild(title_alt);
  tmp.appendChild(title);
  tmp.appendChild(clear_title);
  tmp.appendChild(clear_title_alt);
  tmp.appendChild(keywords_alt);
  tmp.appendChild(keywords);
  tmp.appendChild(description_alt);
  tmp.appendChild(description);
  tmp.appendChild(submit_div);
  tmp.style.width="860px";
  tmp.style.textAlign="left";
  tmp.style.padding="20px";
  tmp.style.paddingTop="0px"
  tmp.id="innerseopanel";
  var center = document.createElement("CENTER");
  center.appendChild(tmp);
  seo.appendChild(center);
  seo.style.overflow="hidden";
  seo.style.height="0px";
  seo.id="seopanel";
  document.body.insertBefore(seo, document.body.firstChild);
  if (seoclosed)
    ajax('/seo/get/'+module+"/"+elem_id+"/"+cat_id,null,null,null,getseoparams)
  } else {
    if (!seoclosed)
        slideclose();
  }
}


function createsupport(cur_url,referer_url,useragent_text,time_text){
  if (!$('supportpanel')){

  $("asupportpanel").setAttribute('style','opacity:0.6;');
  $("asupportpanel").setAttribute("filter", "alpha(opacity=60);");

  var support = document.createElement("DIV");
  var tmp = document.createElement("DIV");
  var form = document.createElement("FORM");
  var result = document.createElement("DIV");
  result.style.paddingTop="5px";
  result.style.paddingBottom="5px";
  result.innerHTML = "&nbsp;";
  result.id="supportresult";
  var description_alt = document.createElement("DIV");
  description_alt.innerHTML = "Описание ошибки";
  description_alt.style.fontSize="12px";
  description_alt.style.fontWeight="bold";
  description_alt.style.paddingBottom="5px";
  description_alt.style.color="#323232";
  var description = document.createElement("TEXTAREA");
  description.name="description";
  description.style.width="600px";
  description.style.height="150px";
  description.style.marginBottom="10px";
  description.id="supportdescription";
  var submit_div = document.createElement("DIV");
  var submit = document.createElement("INPUT");
  submit.type="submit";
  submit.value="Отправить";
  submit.onclick=function(){
    ajax("/raport/send/", "supportresult", "url="+cur_url+"&referer="+referer_url+"&useragent="+useragent_text+"&time="+time_text+"&description="+$('supportdescription').value);
    return false;
  }
  submit_div.appendChild(submit);
  tmp.appendChild(result);
  tmp.appendChild(description_alt);
  tmp.appendChild(description);
  tmp.appendChild(submit_div);
  tmp.style.width="860px";
  tmp.style.textAlign="left";
  tmp.style.padding="20px";
  tmp.style.paddingTop="0px"
  tmp.id="innersupportpanel";
  var center = document.createElement("CENTER");
  center.appendChild(tmp);
  support.appendChild(center);
  support.style.overflow="hidden";
  support.style.height="0px";
  support.style.display="none";
  support.id="supportpanel";
  var firstchild=document.body.firstChild;
  if (firstchild.tagName==undefined) firstchild=firstchild.nextSibling;
  document.body.insertBefore(support, firstchild);
    if (supportclosed){
      if ($("seopanel")) slideclose();

      supportopen();
    }
  } else {
    if (!supportclosed)
        supportclose();
  }
}



