﻿document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

DIY = {
    helpers : function() {
        if(!DIY._helpers) throw "Core helpers module isn't loaded.";
            return DIY._helpers;
    },
    css : function() {
        if(!DIY._cssFactory) throw "Core css module isn't loaded.";
        return DIY._cssFactory;
    },
    events : function() {
        if(!DIY._eventsFactory) throw "Core events module isn't loaded.";
        return DIY._eventsFactory;
    },
    coordinates : function() {
        if(!DIY._coordinatesFactory) throw "Core coordinates module isn't loaded.";
        return DIY._coordinatesFactory;
    },
    autoport : function() {
        if(!DIY._autoport) throw "Autoport module isn't loaded.";
        return DIY._autoport;
    },
    ehsop : function() {
        if(!DIY._eshop) throw "EShop module isn't loaded.";
        return DIY._eshop;
    },
    ui : function() {
        if(!DIY._ui) throw "UI module isn't loaded.";
        return DIY._ui;
    }
}

var uid = (
    function(){
    var id=0;
    return function(){
    return id++ ;
    };
    }
    )();

DIY._ui = {
    fileMax : 10,
    createMultiUploader : function(aploaderName) {        
        var uploader = DIY.helpers().g(aploaderName);
        if(!uploader) return;
        uploader.onchange = function f() {DIY.ui()._addUploaderFile(this, this.fileMax)};
    },
    _addUploaderFile : function(obj, fm) {        
        obj.name = 'optpict*'+DIY.helpers().uid();
        obj.id = obj.name;
        obj.style.display = 'none';
                
        var files_list = document.getElementById('optFiles');
        
        if(!files_list) return;
                
        var v = obj.value;
        var fileInf = document.createElement('p');
        fileInf.className = 'p';
        fileInf.innerHTML = v.substring(v.lastIndexOf("\\")+1);
        files_list.appendChild(fileInf);
        
        var imgSize = document.createElement('select');
        imgSize.name = 'size_'+obj.name;
        imgSize.options[0] = new Option("Логотип", "3");
        imgSize.options[1] = new Option("Маленькое лого", "4");
        imgSize.options[0].selected = 'selected';
        
        fileInf.appendChild(imgSize);
        
        var delBtn = document.createElement('input');
        delBtn.type = 'button';
        delBtn.value = 'Удалить';
        delBtn.className = 'delbtn_varoptimg';
        delBtn.style.marginLeft = '10px';
        delBtn.style.fontSize = 'small';
        delBtn.onclick = function f() {delBtn.disabled = 'true'; obj.parentNode.removeChild(obj); this.parentNode.parentNode.removeChild(this.parentNode);}


        fileInf.appendChild(delBtn);
        
        var uploader = document.createElement('input');
        uploader.type = 'file';
        uploader.id = 'f_uploader';
        uploader.className = 'upload';
        uploader.name = 'fileX[]';
        uploader.size = '20';
        uploader.accept = 'image/jpg,image/gif,image/bmp';
        uploader.onchange = function f() {DIY.ui()._addUploaderFile(this, this.fileMax)};
        obj.parentNode.insertBefore(uploader, obj); 
        
    }
}

DIY._eshop = {
    requiredFields : Array(),
    valideteEditProductForm : function() {
        for(i = 0, n = this.requiredFields.length; i < n; i++) {
            obj = DIY.helpers().g(this.requiredFields[i]);            
            if(obj != null && obj.value == ""){                
                obj.focus();
                alert('Не заполнено обязательное поле!');
                return false;             
            }
        } 
        return true;
    },
    addRequiredField : function(name) {
        this.requiredFields[this.requiredFields.length] = name;
        var o = this.requiredFields        
    },
    showImage : function(title, imagePath) {        
        newWin= open("", "displayWindow", 
        "width=600,height=450,status=yes,toolbar=no,menubar=no,left=400,top=300");
        
        // открыть объект document для последующей печати 
        newWin.focus();
        newWin.document.open();
  
        // генерировать новый документ 
        newWin.document.write("<html><head><style type='text/css'>* { margin : 0px; padding: 0px; cursor: pointer; text-align: center; }</style><title>"+title+"");
        newWin.document.write("</title></head><body onclick='window.close();'>");
        //newWin.document.write("<script src='/Site/js/DIYCore.js' type='text/javascript'></script>");
        newWin.document.write("<img id='img' onload='window.resizeTo(this.width + 30,this.height + 90)' alt='"+title+"' src='"+imagePath+"'></img>");
        newWin.document.write("</body></html>");               
        
        // закрыть документ - (но не окно!)
        newWin.document.close();
        return false;
    },
            createWindow : function(url, name, features, title, html) {
            newWin = window.open(url, name, features);
            
            newWin.focus();
            if ((typeof (url) == 'string' && url.length > 0)) {
                // open url
            }
            else {
                newWin.document.open();
                newWin.document.write("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><style>* { margin: 0; padding: 0; }</style></head><body>");
                newWin.document.write(html);                
                newWin.document.write("</body></html>");
                newWin.document.close();
            }
            return false;
        } ,
    updateImage : function(imgId) {        
        objImg = document.getElementById(imgId);
        if(objImg) {                        
            try
            {
                objImg.src = "VirtImg/RndImg.ashx?rndid=" + Math.floor(Math.random(101)*100);                                
            }
            catch(e) {                
            }            
        }                
    },
    SendData_OptPictEdit : function(sender, e) {
        var delBtns = document.getElementsByClassName('delbtn_varoptimg');        
        for(var i in delBtns){
            delBtns[i].disabled = "true";
        }
    
        var delImgStatus = document.createElement("span");
        delImgStatus.innerHTML = "<font style='color: #F20; margin-left: 10px; font-size: 90%;'>Файл удаляется...</font>";
        sender.parentNode.appendChild(delImgStatus);        
        CallServer_OptPictEditor(e);
    },
    ReceiveServerData_OptPictEdit : function(args, context) {
        objImgInfo = DIY.helpers().g(args);
        
        if(objImgInfo)
            objImgInfo.parentNode.removeChild(objImgInfo);                    
        
        var delBtns = document.getElementsByClassName('delbtn_varoptimg');
        for(var i in delBtns){
            delBtns[i].removeAttribute("disabled");
        }
        
    },
    FilterAlias : function(e, regex) {        
        
        var isIE = (document.all) ? 1 : 0;
        
        var chr = (isIE) ? e.keyCode : e.which;
        
        var ch = String.fromCharCode(chr);
        
        if(isIE && chr == 189)
            return;
        
        if (chr != 13 && chr != 8 && chr != 0 && chr != 39 && chr != 37 && chr != 46 && chr != 36 && chr != 35)
        {
          var re = new RegExp(regex);

          if (ch.search(re) == -1)
          {
             if(isIE)
              e.returnValue = false;
             else
              e.preventDefault();
          }
        }
    }
}

DIY._helpers = {
    AttachEvent : function (objId, eventTypes, func){
        var obj = DIY.helpers().g(objId);
        if(obj==null) return;
        var arrEventType = eventTypes.split(',');
        for(i=0, n = arrEventType.length; i < n; i++){
            var eventType = arrEventType[i];
            if(document.addEventListener){
                obj.addEventListener(eventType, func, false);	    
            }
            else if (document.attachEvent){
                obj.attachEvent('on' + eventType, func);
            }
        }    
    },
    g : function(id) {
        return document.getElementById(id);
    },
    pictRequestCancel : function(){
        var m = document.uniqueID && document.compatMode && !window.XMLHttpRequest && document.execCommand;
        try {
            if(!!m){
                m("BackgroundImageCache", false, true)
            }
        }
        catch(oh){};
    },
    digitFiltering : function(sender, e){
        return true;
        var key;
        var keychar;        
        if (window.event)
            key = window.event.keyCode;
        else if (e)
            key = e.which;
        else
            return true;
        keychar = String.fromCharCode(key);
        // control keys
        if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27))
            return true;
        else if ((("0123456789").indexOf(keychar) > -1))
            return true;          
        else
            return false;            
    },
    fixPNG : function(element) {
        if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
		var src;
		if (element.tagName == 'IMG') {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = "./i/e.gif";
		    }
		} else {
			src = element.currentStyle.backgroundImage
					.match(/url\("(.+\.png)"\)/i)
			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = "none";
			}
		}
		var re_scale_mode = /iesizing\-(\w+)/;
		var m = re_scale_mode.exec(element.className);
		var scale_mode = (m) ? m[1] : 'crop';
		if (src)
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
					+ src + "',sizingMethod='" + scale_mode + "')";
	    }     
    },
    setCookie : function(name, value, expires) {
    if (!expires) {
        expires = new Date();
        }
        document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() +  "; path=/";
    },
    getCookie : function(name) {
        cookie_name = name + "=";
        cookie_length = document.cookie.length;
        cookie_begin = 0;
        while (cookie_begin < cookie_length) {
            value_begin = cookie_begin + cookie_name.length;
            if (document.cookie.substring(cookie_begin, value_begin) == cookie_name) {
                var value_end = document.cookie.indexOf (";", value_begin);
                if (value_end == -1) {
                value_end = cookie_length;
                }
            return unescape(document.cookie.substring(value_begin, value_end));
            }
            cookie_begin = document.cookie.indexOf(" ", cookie_begin) + 1;
            if (cookie_begin == 0) {
                break;
            }
        }
        return null;
        },
    uid : function() {
        return uid();
    }
}

DIY._autoport = {
    slidingMenuShowBtn : function (obj){
        objBtnL = DIY.helpers().g('btn-scroll-left');
        objBtnR = DIY.helpers().g('btn-scroll-right');        
        if(objBtnL && objBtnR) {
            objBtnL.style.display = 'block';
            objBtnR.style.display = 'block';
        }
        obj.isBtnVis = 1;
    },
    slidingMenuInitObject : function (id){
        var obj = DIY.helpers().g(id);
        if (obj) {
            obj.state = 0;
            obj.timer = null;
            obj.maxVert = obj.scrollWidth - obj.offsetWidth;
        }
    },
    slidingMenuScrollLeft : function(id, timer) {
        var obj = DIY.helpers().g(id);
        if(obj){
            if (!obj.maxVert) this.slidingMenuInitObject(id);
            if(!obj.isBtnVis) this.slidingMenuShowBtn(obj);
            
            if (timer == undefined) obj.state = 1;
            if ((obj.maxVert > obj.scrollLeft) && (obj.state == 1)) {
                obj.scrollLeft = obj.scrollLeft + 10;
                obj.timer = setTimeout('DIY.autoport().slidingMenuScrollLeft(\''+id+'\',true)', 16);                
            }
            else {
                objBtn = DIY.helpers().g('btn-scroll-left');
                if(objBtn) {
                    objBtn.style.display = 'none';
                    obj.isBtnVis = 0;
                }
            }
        }
    },
    slidinMenuScrollRight : function(id,timer) {
        var obj = DIY.helpers().g(id);
        if (!obj.maxVert) this.slidingMenuInitObject(id);
        if(!obj.isBtnVis) this.slidingMenuShowBtn(obj);
        
        if (timer == undefined) obj.state = -1;
        if ((obj.scrollLeft > 0) && (obj.state == -1)) {
            obj.scrollLeft = obj.scrollLeft > 10 ? obj.scrollLeft - 10 : 0;
            obj.timer = setTimeout('DIY.autoport().slidinMenuScrollRight(\''+id+'\',true)', 16);
        }
        else {
            objBtn = DIY.helpers().g('btn-scroll-right');
            if(objBtn) {
               objBtn.style.display = 'none'; 
               obj.isBtnVis = 0;
            }
        }
    },    
    slidinMenuScrollStop : function(id) {
        var obj = DIY.helpers().g(id);
        if (obj) {
            if (obj.timer) clearTimeout(obj.timer);
            obj.state = 0;
                        
            expires = new Date();
            expires.setTime(expires.getTime() + (1000 * 86400 * 365));            
            DIY.helpers().setCookie("sMenuPos", obj.scrollLeft, expires);
        }        
    },
    initSlidingMenu : function (id){
        objBtnL = DIY.helpers().g('btn-scroll-left');
        objBtnR = DIY.helpers().g('btn-scroll-right');
        
        var obj = DIY.helpers().g(id);
        if(obj) {
            obj.scrollLeft = parseInt(DIY.helpers().getCookie("sMenuPos"), 10);            
            if(objBtnL && objBtnR) {
                var v1 = obj.scrollWidth - obj.offsetWidth;
                if(v1 > obj.scrollLeft)
                    objBtnL.style.display = 'block';                                    
                if(v1 >= obj.scrollLeft && obj.scrollLeft != 0) {
                    objBtnR.style.display = 'block';
                }
            }
        }
    }
}

function KeyUpHandler(senderID, controlID)
{
    sender = document.getElementById(senderID);
    
    if(null != senderID)
		sender.focus();
    
    if (event.keyCode != 13)
		return;
		
	event.returnValue = false;
	event.cancelBubble = true;
	event.keyCode = 0;

	if (null != controlID)
	{
		control = document.getElementById(controlID);

		if (null != control)
			control.click();
	}
	else
		return false;
}

//function g(Id)
//{
//    return document.getElementById(Id);
//}

//function iP_EnableMaxMin(oBtn, sContentId)
//{
//    oBtn.blur();
//    var oContent = g(sContentId);
//    if(oContent!=null)
//    {        
//        if(oContent.style.display=='none' || oContent.style.display=='')
//        {
//            oContent.style.display = 'block';
//        }
//        else
//        {
//            oContent.style.display='none';
//        }
//        return true; //cancel postback
//    }
//    return false; //failed so do postback
//}

//function iP_EnablePopup(oBtn, sContentId)
//{
//    //oBtn.blur();
//    var oContent = g(sContentId);
//    if(oContent != null)
//    {
//        if(oContent.style.display=='none')
//        {            
//            oContent.style.position = 'absolute';
//            oContent.style.left = window.event.x;
//            oContent.style.top = window.event.y;
//            oContent.style.display = 'block';
//            oContent.focus();            
//            //oBtn.onmouseout = new Function("return new function hide() {obj = g('"+sContentId+"'); if(obj!=null){obj.style.display='none'}; }");
//            oContent.onblur = new Function("return new function hide() {obj = g('"+sContentId+"'); if(obj!=null){obj.style.display='none'}; }");
//        }
//        return true;
//    }
//    return false;
//}

///* Styling radio elements */

//diyMakePizdato = {

//userAgent: '',
//isSafari: false,
//init: function()
//    {        
//        this.userAgent = navigator.userAgent.toLowerCase();
//        this.isSafari = ((this.userAgent.indexOf('safari')!=-1) && this.userAgent.indexOf('mac')!=-1)?true:false;
//        if(!this.isSafari)
//        {
//            arrLabels = document.getElementsByTagName('label');            
//            
//            for(var i=0; i<arrLabels.length; i++)
//            {
//                if(arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value!='')
//                {
//                    labelFor = arrLabels[i].getAttributeNode('for').value;
//                    inpElem = g(labelFor);                    
//                    if(inpElem!=null)
//                    {
//                        inpElemType = inpElem.getAttributeNode('type').value;
//                        switch(inpElemType)
//                        {                            
//                            case 'radio':
//                                arrLabels[i].style.cursor = 'pointer';
//                                arrLabels[i].style.cursor = 'hand';
//                                inpElem.style.position = 'absolute';
//                                inpElem.style.left = '-2000px';
//                                if(inpElem.onclick==null)
//                                {
//                                    inpElem.onclick = diyMakePizdato.toggleRadio;
//                                }                                
//                                // initial label state
//                                if(inpElem.checked)
//                                {
//                                    arrLabels[i].className = 'radioChecked';
//                                }
//                                else
//                                {
//                                    arrLabels[i].className = 'radioUnchecked';
//                                }
//                                break
//                            case 'checkbox':
//                                arrLabels[i].style.cursor = 'pointer';
//                                arrLabels[i].style.cursor = 'hand';
//                                inpElem.style.position = 'absolute';
//                                inpElem.style.left = '-2000px';
//                                if(inpElem.onclick==null)
//                                {
//                                    inpElem.onclick = diyMakePizdato.toggleChechBox;
//                                }
//                                // initial label state
//                                if(inpElem.checked)
//                                {
//                                    arrLabels[i].className = 'checkBoxChecked';
//                                }
//                                else
//                                {
//                                    arrLabels[i].className = 'checkBoxUnchecked';
//                                }
//                                break
//                        }
//                    }                 
//                }
//            }
//            
//        }
//    },
//findLabel: function(labelId, typeName)
//{    
//    var arrLabels = document.getElementsByTagName('label');
//    var fLabel = null;
//    switch (typeName)
//    {
//        case 'radio':
//            for(var i = 0; i < arrLabels.length; i++)
//            {        
//                if (arrLabels[i].getAttributeNode('for'))
//                {            
//                    var objInput = g(arrLabels[i].getAttributeNode('for').value);
//                    if(objInput !=null && objInput.getAttributeNode('type').value == 'radio')
//                    {
//                        arrLabels[i].className = 'radioUnchecked';
//                        if(arrLabels[i].getAttributeNode('for').value == labelId)
//                        {        
//                            fLabel = arrLabels[i];
//                        }
//                    }            
//                }
//            }
//            break
//        case 'checkbox':
//            for(var i = 0; i < arrLabels.length; i++)
//            {
//                var objInput = g(arrLabels[i].getAttributeNode('for').value);
//                if(objInput != null && objInput.getAttributeNode('type').value == 'checkbox')
//                {
//                    if(arrLabels[i].getAttributeNode('for').value == labelId)
//                    {
//                        fLabel = arrLabels[i];
//                        break;
//                    }                                     
//                }
//            }
//            break
//    }
//    return fLabel;
//},
//toggleChechBox: function()
//{    
//    this.blur();
//    objLabel = diyMakePizdato.findLabel(this.getAttributeNode('id').value, this.getAttributeNode('type').value);
//    if(objLabel != null)
//    {
//        if(objLabel.className == 'checkBoxChecked')
//        {
//            objLabel.className = 'checkBoxUnchecked';
//        }
//        else
//        {
//            objLabel.className = 'checkBoxChecked';
//        }
//    }
//},
//toggleRadio: function()
//    {
//        this.blur(); 
//        objLabel = diyMakePizdato.findLabel(this.getAttributeNode('id').value, this.getAttributeNode('type').value);                         
//        if(objLabel != null)
//        {
//            objLabel.className = 'radioChecked';                                        
//        }        
//    },     
//addEvent: function(elem, eventType, doFunction, useCapture)
//    {
//        if(elem.addEventListener)
//        {
//            elem.addEventListener(eventType, doFunction, useCapture);
//            return true;
//        }
//        else if(elem.attachEvent)
//        {
//            var r = elem.attachEvent('on' + eventType, doFunction);
//            return r;
//        }
//        else
//        {                        
//            elem['on'+eventType] = doFunction;
//        }
//    }    
//};

//// diyMakePizdato.addEvent(window, 'load', diyMakePizdato.init, false);











//// Test
//function stylesSelect()
//{
//    var arrSelects = document.getElementsByTagName('select');
//    var arrLen = arrSelects.length;
//    for (var i = 0; i < arrLen; i++)
//    {
//        replaceSelect(arrSelects[i]);        
//    }
//}

//function replaceSelect(objSelect)
//{       
//    var objUl = document.createElement('ul');
//    
//    objUl.className = 'select';
//    
//    // add linkage
//    objUl.linkage = objSelect;
//    objSelect.linkage = objUl;
//    
//    objSelect.className = 'replacedSelect';
//    
//    var opt = objSelect.options;
//    var optLen = opt.length;
//    
//    for (var i = 0; i < optLen; i++)
//    {
//        var li = document.createElement('li');
//        li.appendChild(document.createTextNode(opt[i].text));
//        li.index = i;
//        objUl.appendChild(li);
//    }
//    
//    objUl.selectLi = function(objLi)
//    {
//        var objUl = objLi.parentNode;
//        if(objUl.selectedIndex != null)
//            objUl.childNodes[ul.selectedIndex].cssClass = '';
//            
//        objUl.selectedIndex = objLi.index;
//        objUl.childNodes[objLi.index].className = 'selectedLi';            
//    }
//    
//    if(objSelect.selectIndex == null)
//        objSelect.selectIndex = 0;
//    
//    objUl.selectLi(objUl.childNodes[objSelect.selectIndex]);
//    
//    objSelect.parentNode.insertBefore(objUl, objSelect);    
//}
