function $(elem)
{
    return document.getElementById(elem);
}

//print_r for object state; modeparam can be 'inline' or 'newline'
function print_r(obj, mode)
{
    html="";

    for(var i in obj) {
        if(mode == 'inline')
            html += i + " = " + obj[i] + ";  ";
        else
            html += i + " = " + obj[i] + "\n";
    }
    alert(html);
}

rs = {
    req : null,
    readystate : 0,
    responce : null,
    onreadystatechange: null,

    obtain_xml : function(url) {
        if (window.XMLHttpRequest) {
            try {
                rs.req = new XMLHttpRequest()
            } catch(e) {}
        } else if (window.ActiveXObject) {
            try {
                rs.req = new ActiveXObject("Microsoft.XMLHTTP")
            } catch(e) {}
            if (!rs.req) try {
                rs.req = new ActiveXObject("Msxml2.XMLHTTP")
            } catch (e) {}
        }
        if (rs.req) {
            // var th = this;
            rs.req.onreadystatechange = function() {
                var s = rs.req.readyState;
                if (s == 4) {
                    // Avoid memory leak by removing closure.
                    //  rs.req.onreadystatechange = th.dummy;
                    // Remove possible junk from response.
                    var responseText = rs.req.responseText;
                    eval(responseText);
                }
            }
            rs.req.open("GET", url, true);
            rs.req.send(null);
        }
    },

    obtain_script : function(url) {
        var head = document.getElementsByTagName("head")[0];
        var sObj = document.createElement( 'script' );
        sObj.src = url;
        sObj.id = 'remote_script';
        if (head.getElementsByTagName('script')[0]) {
            var a = document.getElementsByTagName("script")[0];
            head.insertBefore( sObj, a );
        } else {
            head.appendChild( sObj );
        }
    },

    dataready: function(js) {
        if(js !== null) {
            rs.readystate = 4;
            rs.response = js;
        }
        if (rs.onreadystatechange) rs.onreadystatechange();
    //var parent = $('remote_script').parentNode;
    //parent.replaceChild(sObj);
    },

    process : function(url, callback, onloading, onload_param) {
        if(onloading){
            if (onload_param)
                onloading(onload_param);
            else
                onloading();
        }
        rs.onreadystatechange = callback;

        if (window.XMLHttpRequest || window.ActiveXObject)
            rs.obtain_xml(url);
        else
            rs.obtain_script(url);
    }
}

function createPopup(id, hor_size, vert_size){
    var body = document.getElementsByTagName("body")[0];
    var div = document.createElement( 'div' );
    div.id = id;

    var y_coord = (document.documentElement.scrollTop + screen.availHeight/2) - vert_size;
    var x_coord = screen.width/2 - hor_size/2;

    div.setAttribute('style', 'background: white; z-index: 100; position: absolute; top:'+Math.ceil(y_coord)+'px; left:'+Math.ceil(x_coord)+'px;');
    div.style.background = 'white';
    div.style.top = y_coord;
    div.style.left = x_coord;
    div.style.position = 'absolute';

    body.appendChild(div);

    return div;
}

var hog = 0;
var dx;
var dy;

function drag_n_drop(dragged_obj)
{
    var obj = dragged_obj;

    switch(event.type) {
        case 'mouseover':
            obj.style.cursor = 'move';
            break;

        case 'mousedown':

            hog = 1;
            dx = event.offsetX;
            dy = event.offsetY;
            break;

        case 'mousemove':
            if(hog == 1) {
                obj.style.left = event.x - dx;
                obj.style.top = event.y - dy;
            }
            break;

        case 'mouseup':
            if(hog != 0)
                hog = 0;
            break;
    }

}

function pause(timeout)
{
    var date = new Date();
    var curDate = null;
    do {
        var curDate = new Date()
        }
    while(curDate-date < timeout)
}

function number_format(a, b, c, d) {
    a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
    e = a + '';
    f = e.split('.');
    if (!f[0]) {
        f[0] = '0';
    }
    if (!f[1]) {
        f[1] = '';
    }
    if (f[1].length < b) {
        g = f[1];
        for (i=f[1].length + 1; i <= b; i++) {
            g += '0';
        }
        f[1] = g;
    }
    if(d != '' && f[0].length > 3) {
        h = f[0];
        f[0] = '';
        for(j = 3; j < h.length; j+=3) {
            i = h.slice(h.length - j, h.length - j + 3);
            f[0] = d + i +  f[0] + '';
        }
        j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
        f[0] = j + f[0];
    }
    c = (b <= 0) ? '' : c;
    return f[0] + c + f[1];
}

function retrieveCookie( cookieName ) {
    var cookieJar = document.cookie.split( "; " );
    for( var x = 0; x < cookieJar.length; x++ ) {
        var oneCookie = cookieJar[x].split( "=" );
        if( oneCookie[0] == escape( cookieName ) ) {
            return oneCookie[1] ? unescape( oneCookie[1] ) : '';
        }
    }
    return null;
}

function setCookie( cookieName, cookieValue, lifeTime, path, domain, isSecure ) {
    if( !cookieName ) {
        return false;
    }
    if( lifeTime == "delete" ) {
        lifeTime = -10;
    } //this is in the past. Expires immediately.
    document.cookie = escape( cookieName ) + "=" + escape( cookieValue ) +
    ( lifeTime ? ";expires=" + ( new Date( ( new Date() ).getTime() + ( 1000 * lifeTime ) ) ).toGMTString() : "" ) +
    ( path ? ";path=" + path : "") + ( domain ? ";domain=" + domain : "") +
    ( isSecure ? ";secure" : "");
    //check if the cookie has been set/deleted as required
    if( lifeTime < 0 ) {
        if( typeof( retrieveCookie( cookieName ) ) == "string" ) {
            return false;
        }
        return true;
    }
    if( typeof( retrieveCookie( cookieName ) ) == "string" ) {
        return true;
    }
    return false;
}

var FS_INCLUDE_NAMES = 0, FS_EXCLUDE_NAMES = 1, FS_INCLUDE_IDS = 2, FS_EXCLUDE_IDS = 3, FS_INCLUDE_CLASSES = 4, FS_EXCLUDE_CLASSES = 5;

function getFormString( formRef, oAndPass, oTypes, oNames ) {
    if( oNames ) {
        oNames = new RegExp((( oTypes > 3 )?'\\b(':'^(')+oNames.replace(/([\\\/\[\]\(\)\.\+\*\{\}\?\^\$\|])/g,'\\$1').replace(/,/g,'|')+(( oTypes > 3 )?')\\b':')$'),'');
        var oExclude = oTypes % 2;
    }
    for( var x = 0, oStr = '', y = false; formRef.elements[x]; x++ ) {
        if( formRef.elements[x].type ) {
            if( oNames ) {
                var theAttr = ( oTypes > 3 ) ? formRef.elements[x].className : ( ( oTypes > 1 ) ? formRef.elements[x].id : formRef.elements[x].name );
                if( ( oExclude && theAttr && theAttr.match(oNames) ) || ( !oExclude && !( theAttr && theAttr.match(oNames) ) ) ) {
                    continue;
                }
            }
            var oE = formRef.elements[x];
            var oT = oE.type.toLowerCase();
            if( oT == 'text' || oT == 'textarea' || ( oT == 'password' && oAndPass ) || oT == 'datetime' || oT == 'datetime-local' || oT == 'date' || oT == 'month' || oT == 'week' || oT == 'time' || oT == 'number' || oT == 'range' || oT == 'email' || oT == 'url' ) {
                oStr += ( y ? ',' : '' ) + oE.value.replace(/%/g,'%p').replace(/,/g,'%c');
                y = true;
            } else if( oT == 'radio' || oT == 'checkbox' ) {
                oStr += ( y ? ',' : '' ) + ( oE.checked ? '1' : '' );
                y = true;
            } else if( oT == 'select-one' ) {
                oStr += ( y ? ',' : '' ) + oE.selectedIndex;
                y = true;
            } else if( oT == 'select-multiple' ) {
                for( var oO = oE.options, i = 0; oO[i]; i++ ) {
                    oStr += ( y ? ',' : '' ) + ( oO[i].selected ? '1' : '' );
                    y = true;
                }
            }
        }
    }
    return oStr;
}

function recoverInputs( formRef, oStr, oAndPass, oTypes, oNames ) {
    if( oStr ) {
        oStr = oStr.split( ',' );
        if( oNames ) {
            oNames = new RegExp((( oTypes > 3 )?'\\b(':'^(')+oNames.replace(/([\\\/\[\]\(\)\.\+\*\{\}\?\^\$\|])/g,'\\$1').replace(/,/g,'|')+(( oTypes > 3 )?')\\b':')$'),'');
            var oExclude = oTypes % 2;
        }
        for( var x = 0, y = 0; formRef.elements[x]; x++ ) {
            if( formRef.elements[x].type ) {
                if( oNames ) {
                    var theAttr = ( oTypes > 3 ) ? formRef.elements[x].className : ( ( oTypes > 1 ) ? formRef.elements[x].id : formRef.elements[x].name );
                    if( ( oExclude && theAttr && theAttr.match(oNames) ) || ( !oExclude && ( !theAttr || !theAttr.match(oNames) ) ) ) {
                        continue;
                    }
                }
                var oE = formRef.elements[x];
                var oT = oE.type.toLowerCase();
                if( oT == 'text' || oT == 'textarea' || ( oT == 'password' && oAndPass ) || oT == 'datetime' || oT == 'datetime-local' || oT == 'date' || oT == 'month' || oT == 'week' || oT == 'time' || oT == 'number' || oT == 'range' || oT == 'email' || oT == 'url' ) {
                    oE.value = oStr[y].replace(/%c/g,',').replace(/%p/g,'%');
                    y++;
                } else if( oT == 'radio' || oT == 'checkbox' ) {
                    oE.checked = oStr[y] ? true : false;
                    y++;
                } else if( oT == 'select-one' ) {
                    oE.selectedIndex = parseInt( oStr[y] );
                    y++;
                } else if( oT == 'select-multiple' ) {
                    for( var oO = oE.options, i = 0; oO[i]; i++ ) {
                        oO[i].selected = oStr[y] ? true : false;
                        y++;
                    }
                }
            }
        }
    }
}

function saveuser11data() {
    setCookie( 'user11data', getFormString( $('cart_form'), false, FS_INCLUDE_NAMES, 'user_discount,user_name,user_phone,user_city,user_email,user_address,org_title,org_address,org_unp,org_phones,org_bank_account,org_bank,org_company_head,org_work_reason,user_text' ), 15552000 );
}

function newImage(arg) {
    if (document.images) {
        rslt = new Image();
        rslt.src = arg;
        return rslt;
    }
}

function changeImages() {
    if (document.images && (preloadFlag == true)) {
        for (var i=0; i<changeImages.arguments.length; i+=2) {
            document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
        }
    }
}

var preloadFlag = false;
function preloadImages() {
    if (document.images) {
        lazer_over = newImage("/img/lazer-over.gif");
        inkjet_over = newImage("/img/inkjet-over.gif");
        paper_over = newImage("/img/paper-over.gif");
        acc_over = newImage("/img/acc-over.gif");

        preloadFlag = true;
    }
}

var active_tab = 1 ;
//var active_group = [];
scrollStep=1
timerLeft=""
timerRight=""

function toLeft(id){
    document.getElementById(id).scrollLeft=0
}

function scrollDivLeft(id){
    clearTimeout(timerRight)
    document.getElementById(id).scrollLeft+=scrollStep
    timerRight=setTimeout("scrollDivLeft('"+id+"')",10)
}

function scrollDivRight(id){
    clearTimeout(timerLeft)
    document.getElementById(id).scrollLeft-=scrollStep
    timerLeft=setTimeout("scrollDivRight('"+id+"')",10)
}

function toRight(id){
    document.getElementById(id).scrollLeft=document.getElementById(id).scrollWidth
}

function stopMe(){
    clearTimeout(timerRight)
    clearTimeout(timerLeft)
}

function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

var getElementsByClassName = function (className, tag, elm){
    if (document.getElementsByClassName) {
        getElementsByClassName = function (className, tag, elm) {
            elm = elm || document;
            var elements = elm.getElementsByClassName(className),
            nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
            returnElements = [],
            current;
            for(var i=0, il=elements.length; i<il; i+=1){
                current = elements[i];
                if(!nodeName || nodeName.test(current.nodeName)) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    else if (document.evaluate) {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
            classesToCheck = "",
            xhtmlNamespace = "http://www.w3.org/1999/xhtml",
            namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
            returnElements = [],
            elements,
            node;
            for(var j=0, jl=classes.length; j<jl; j+=1){
                classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
            }
            try	{
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
            }
            catch (e) {
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
            }
            while ((node = elements.iterateNext())) {
                returnElements.push(node);
            }
            return returnElements;
        };
    }
    else {
        getElementsByClassName = function (className, tag, elm) {
            tag = tag || "*";
            elm = elm || document;
            var classes = className.split(" "),
            classesToCheck = [],
            elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
            current,
            returnElements = [],
            match;
            for(var k=0, kl=classes.length; k<kl; k+=1){
                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
            }
            for(var l=0, ll=elements.length; l<ll; l+=1){
                current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
                    match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};

function toggleSingleFilter(e, item) {
    var checkboxes = document.getElementsByName('formats_show');
    for(i=0;i<checkboxes.length;i++)
        if(checkboxes[i].value != item)
            checkboxes[i].checked = false;
        else
            checkboxes[i].checked = true;
    switchLiveFilter(e);
}


function toggleAllFiltersOn(e) {
    var checkboxes = document.getElementsByName('formats_show');
    for(i=0;i<checkboxes.length;i++) {
        checkboxes[i].checked = true;
    }
}

function switchLiveFilter(e)    {
    var checkboxes = document.getElementsByName('formats_show');
    if(checkboxes === undefined || checkboxes.length<1)
        return false;
    var stockbox = document.getElementsByName('outofstock_show');
    var starter = getElementsByClassName('starters'+String(active_tab));
    var subintro = [];
    for(j=0;j<starter.length;j++){
        newintro = getElementsByClassName('subgroup','tr',starter[j]);
        if(newintro) subintro.push(newintro[0]);
    }
    showoutofstock = false;

    if(stockbox[0].checked) {
        style_out = "";
        showoutofstock = true;
    } else {
        style_out = "none";
        showoutofstock = false;
    }
    // var subintro = getElementsByClassName('subgroup','tr',starter[0]);
    for(i=0;i<checkboxes.length;i++) {
        for(l=0;l<subintro.length;l++) {
            if(subintro[l].style.display != "none") {

                var products_out = getElementsByClassName('products'+String(active_tab)+' '+
                    subintro[l].className.replace(" subgroup","")+
                    ' outofstock'+' '+checkboxes[i].value,'tr');
                selection =  'products'+String(active_tab)+' '+subintro[l].className.replace(" subgroup","")+
                ' '+checkboxes[i].value;
                var products = getElementsByClassName(selection,'tr');
                if(checkboxes[i].checked) {
                    display_style = "";
                } else {
                    display_style = "none";
                }
                for(k=0;k<products_out.length;k++) {
                    products_out[k].style.display = style_out;
                }
                for(k=0;k<products.length;k++) {
                    product_stock = products[k].className.search("outofstock") ;
                    if((product_stock != -1) && !showoutofstock) {
                        products[k].style.display = "none";
                    } else {
                        products[k].style.display = display_style;
                    }
                }
            }
        }

    }
}

function switchTabs(e, itab){
    var tabs = document.getElementById('ultabs').getElementsByTagName('li');
    var dtabs = document.getElementById('ultabs').getElementsByTagName('div');
    //  var devspan = document.getElementById('devbar').getElementsByTagName('div');
    var ultabs = document.getElementById('ultabs');
    if((itab+1) == active_tab) {
        var newstarters = getElementsByClassName('starters'+String(itab+1));
        var newgoods = getElementsByClassName('products'+String(itab+1));
        var newintros = [];
        for(j=0;j<newstarters.length;j++){
            subintros = getElementsByClassName('subgroup','tr',newstarters[j]);
            if(subintros) newintros.push(subintros[0]);
        }
        if(newintros[0]) {
            if(newintros[0].style.display == "none")
                display_style = "";
            else
                display_style = "none";
        }
        for(j=0;j<newintros.length;j++)
            if(newintros[j])
                newintros[j].style.display = display_style;
        for(j=0;j<newgoods.length;j++)
            if(newgoods[j])
                newgoods[j].style.display = display_style;

    } else {
        var newgoods = getElementsByClassName('products'+String(itab+1));
        var newstarters = getElementsByClassName('starters'+String(itab+1));
        var newintros = [];
        var oldgoods = getElementsByClassName('products'+String(active_tab));
        var oldstarters = getElementsByClassName('starters'+String(active_tab));
        var oldintros = [];
        var subintros = [];
        var twidth = getStyle('tabbar','width');
        var ttwidth = getStyle('suptabs','width');
        i=1;
        for(j=0;j<tabs.length;j++){
            tabs[j].className = "tab"+i;
            i++;
        }
        for(j=0;j<oldgoods.length;j++){
            oldgoods[j].style.display = "none";
        }
        for(j=0;j<oldstarters.length;j++){
            oldstarters[j].style.display = "none";
            subintros = getElementsByClassName('subgroup','tr',oldstarters[j]);
            if(subintros) oldintros.push(subintros[0]);
        }
        for(j=0;j<newgoods.length;j++){
            newgoods[j].style.display = "";
        }
        for(j=0;j<newstarters.length;j++){
            newstarters[j].style.display = "";
            subintros = getElementsByClassName('subgroup','tr',newstarters[j]);
            if(subintros) newintros.push(subintros[0]);
        }
        for(j=0;j<oldintros.length;j++){
            if(oldintros[j]) oldintros[j].style.display = "none";
        }
        for(j=0;j<newintros.length;j++){
            if(newintros[j]) newintros[j].style.display = "";
        }
    }
    tabs[itab].className = "tab"+String(itab+1)+" selected";
    ultabs.style.whiteSpace = "nowrap";
    document.getElementById('tabbar').style.width=twidth;
    document.getElementById('suptabs').style.width=ttwidth;
    active_tab = itab+1 ;
    switchLiveFilter(e);
}

function showhideSubgroup(e, group){
    //var oldgoods = getElementsByClassName('products'+String(active_tab));
    // oth
    var goods = getElementsByClassName('subgroup'+String(group));
    // var starter = getElementsByClassName('starters'+String(group));
    //var starters = getElementsByClassName('starters'+String(group));
    //var oldstarters = getElementsByClassName('starters'+String(active_tab));
    //var twidth = getStyle('tabbar','width');
    //var ttwidth = getStyle('suptabs','width');
    //var subintro = getElementsByClassName('subgroup','tr',starter[0]);
    if(goods[0].style.display == "none")
        display_style = "";
    else
        display_style = "none";
    for(j=0;j<goods.length;j++)
        goods[j].style.display = display_style;
    switchLiveFilter(e);
}

var pictoffset;
function opendd(event, ID)
{
    //	document.getElementById(ID).style.display='';

    //print_r(event, 'inline');
    var topbox = $(ID + 'topbox');

    var obj = (window.getComputedStyle && !window.opera)?event.target:event.srcElement;
    //print_r(obj, 'inline');
    var td = obj.parentNode.parentNode;
    //print_r(td, 'inline');
    if(obj.nodeName == 'IMG') {
        pictoffset = td.offsetLeft + obj.offsetLeft;
    }
    Position();


    var tableoffset = parseInt($(ID).style.left);

    //if (Mozilla)
    if(obj.nodeName == 'IMG' && obj.id == ID+'img') {
        //print_r(topbox, 'inline');
        //print_r(topbox.previousSibling, 'inline');
        //print_r(navigator, 'inline');

        //if(topbox.previousSibling && topbox.previousSibling.nodeName != "#text") {
        if(window.getComputedStyle && !window.opera) {

            if(topbox.previousSibling.previousSibling) {
                topbox.previousSibling.previousSibling.width = (pictoffset - tableoffset - 1) + 'px';
            //alert(topbox.previousSibling.width);
            } else {
                $(ID).style.left = pictoffset - 2 + 'px';
            }

            topbox.width = 95 + 1;


        } else {
            if(topbox.previousSibling && topbox.previousSibling.nodeName != "#text") {
                topbox.previousSibling.width = (pictoffset - tableoffset - 1) + 'px';
            //alert(topbox.previousSibling.width);
            } else {
                $(ID).style.left = pictoffset - 2 + 'px';
            }

            topbox.width = 96 + 1;
        }
    }


    show = "document.getElementById('" + ID + "').style.display = ''";
    time = setTimeout(show,50);
}

function closedd(ID)
{
    //	document.getElementById(ID).style.display='none';
    Position();

    show = "document.getElementById('" + ID + "').style.display = 'none'";
    time = setTimeout(show,50);
}

function stopTimeOut()
{
    clearTimeout(time);
}

function Position()
{
    var mid = document.body.scrollWidth/2;

    //document.getElementById('dd1').style.left=0.02*mid+'px';
    document.getElementById('dd2').style.left=0.02*mid+'px';
    document.getElementById('dd3').style.left=0.02*mid+'px';
    document.getElementById('dd4').style.left=0.02*mid+'px';

    document.getElementById('dd1').style.width=mid-0.02*mid+'px';
    document.getElementById('dd2').style.width=mid-0.02*mid+'px';
    document.getElementById('dd3').style.width=mid-0.02*mid+'px';
    document.getElementById('dd4').style.width=mid-0.02*mid+'px';


}

var doublefire = false;

var fastsearch = {

    printer_type : null,
    printer_brand : null,
    printer_model : null,
    link: null,

    onloading_clbk : function(select_elem)
    {
        if(select_elem)
            $(select_elem).options[0] = new Option('Загрузка...', 'loading', true, false);

    },
    show_brands : function() {

        data = rs.response;
        fastsearch.clear_result(['printer_brand']);
        select = new Option('Выберите бренд: ', 'select', true, false);
        $('printer_brand').options[0] = select;
        for(i=0; i<data.length; i++) {
            $('printer_brand').options[i+1] = new Option(data[i], data[i], false, false);
        }

    },
    show_models : function(){
        data = rs.response;
        fastsearch.clear_result(['printer_model']);
        select = new Option('Выберите модель: ', 'select', true, false);
        $('printer_model').options[0] = select;

        for(i=0; i<data.length; i++) {
            $('printer_model').options[i+1] = new Option(data[i].serie +" "+ data[i].model, data[i].serie+"_"+data[i].model, false, false);
        }

    },
    clear_result : function(params){
        for( i=0; i<params.length; i++) {
            $(params[i]).options.length = 0;
        }

        $('fastsearch_link').href = 'javascript:void()';
    },

    create_link : function(){

        fastsearch.save_state();
        $('fastsearch_link').href = '/products/show/printer_type:' + fastsearch.printer_type + '/printer_brand:' + fastsearch.printer_brand + '/printer_serie:' + fastsearch.printer_serie +'/printer_model:' + fastsearch.printer_model;
    },

    test : function() {
    //alert('fastacess test!');
    },

    onChangeHandler : function(event,e) {
        if(doublefire) {
            return true;
        }
        doublefire = true;
        var nodoublefire = setTimeout("doublefire = false;",1000);

        obj = (window.getComputedStyle && !window.opera)? event.target : event.srcElement;
        switch(obj.id) {
            case 'printer_type':
                fastsearch.clear_result(['printer_model', 'printer_brand']);
                if($('printer_type').options[$('printer_type').selectedIndex].value != 'select') {
                    fastsearch.printer_type = $('printer_type').options[$('printer_type').selectedIndex].value;
                    url = '/rest_services/fastsearch/brand_list/' + fastsearch.printer_type;
                    rs.process(url, fastsearch.show_brands, fastsearch.onloading_clbk, 'printer_brand');
                }
                break;

            case 'printer_brand':
                fastsearch.clear_result(['printer_model']);
                if($('printer_brand').options[$('printer_brand').selectedIndex].value != 'select') {
                    fastsearch.printer_brand = $('printer_brand').options[$('printer_brand').selectedIndex].value;
                    if(fastsearch.printer_type == null)
                        fastsearch.printer_type = $('printer_type').options[$('printer_type').selectedIndex].value;
                    url = '/rest_services/fastsearch/model_list/' + fastsearch.printer_type + '/' + fastsearch.printer_brand;
                    rs.process(url, fastsearch.show_models, fastsearch.onloading_clbk, 'printer_model');
                }
                break;

            case 'printer_model':
                if($('printer_model').options[$('printer_model').selectedIndex].value != 'select') {
                    if(fastsearch.printer_type == null)
                        fastsearch.printer_type = $('printer_type').options[$('printer_type').selectedIndex].value;
                    if(fastsearch.printer_brand == null)
                        fastsearch.printer_brand = $('printer_brand').options[$('printer_brand').selectedIndex].value;

                    var printer_model_serie = $('printer_model').options[$('printer_model').selectedIndex].value;
                    param_arr = printer_model_serie.split("_");
                    fastsearch.printer_serie = param_arr[0];
                    fastsearch.printer_model = param_arr[1];
                    fastsearch.create_link();
                }
                break;
        }
    },

    save_state : function()
    {
        url = '/rest_services/save_fastsearch_state/' + fastsearch.printer_type + '/' + fastsearch.printer_brand + '/' + fastsearch.printer_model + '/' + fastsearch.printer_serie;
        rs.process(url, function(){});
    }

}

var cart = {

    delivery_type : 'courier',
    payment_type : null,
    popup: null,
    new_id: null,
    popup_id: 'temp_div',
    popup_opened: false,
    discount_calculated : false,
    discount_value : null,
    types_map : null,
    base_prices : [],
    base_totals : [],
    close_delay_secs : 5,
    netsum: 0,

    add: function(id) {
        cart.new_id = id;
        count = $(cart.new_id+'_count').value;
        stock = $(cart.new_id+'_stock').value;

        // fixing a comparison bug
        count = Math.abs(count);
        stock = Math.abs(stock);
        //if(!isNaN(count)){
        if(count <= stock){
            url = '/rest_services/cart/add/'+cart.new_id+'_'+count;
            rs.process(url, cart.was_added, cart.please_wait)
        } else {
            alert('Такого количества товара нет на складе (надо '+count+', в наличии '+stock+') '+cart.new_id);
        } /* } else {
			url = '/rest_services/cart/add/'+cart.new_id+'_'+count;
			rs.process(url, cart.was_added, cart.please_wait)
		} */
    },

    helper_update: function() {
        new_count = $(cart.new_id+'_count').value;
        new_cost_s = $(cart.new_id+'_cost').innerHTML;
        new_cost = new_cost_s.replace(/[^0-9]/g, '');
        old_count = $('helper_cart_count').innerHTML;
        old_sum_s = $('helper_cart_sum').innerHTML;
        old_sum = old_sum_s.replace(/[^0-9]/g, '');
        $('helper_cart_count').innerHTML = '';
        $('helper_cart_count').innerHTML= (parseInt(old_count) + parseInt(new_count));
        $('helper_cart_sum').innerHTML = '';
        $('helper_cart_sum').innerHTML = number_format((parseInt(old_sum) + (parseInt(new_count) * parseInt(new_cost))),0,",","'");
    },

    please_wait: function() {

        var body = document.getElementsByTagName("body")[0];
        var div = document.createElement( 'div' );
        div.id = cart.popup_id;
        //div.setAttribute('style', 'position: absolute; top: 200px; left: 200px;');
        cart.popup = createPopup(cart.popup_id, 311, 200)
        if(cart.popup !=null)
            cart.popup_opened = true;

        /*var html = '<table width="311" border="0" cellpadding="0" cellspacing="0" style="border:1px solid #909090;">'
		html +=		'<tr>';
		html += 	'<td colspan="2" valign="top" background="/img/zak_pt.gif" height="39" align="right" style="border:1px solid #fff;"><a href="#"><img src="/img/zak_but.gif" alt="" border="0" width="21" height="21" style="margin:2px;" /></a></td>';
		html +=     '</tr><tr>';
		html +=		'<td height="120" colspan="2" align="center" valign="middle">';
		html +=		'<div><img src="/img/wait.gif" alt="" /></div>';
		html +=		'<div style=" margin-top:2px;"><img src="/img/trash.gif" alt="" /></div>';
		html +=		'</td></tr></table>';	*/
        var obj = cart.popup
        obj.innerHTML = $('please_wait').innerHTML;

    //$('please_wait').innerHTML = '';
    },

    was_added: function()
    {
        if (rs.response == null) {
            //alert ('Error!!');
            if(popup_opened)
                cart.close_popup();

            return;
        }
        cart.helper_update();

        if(cart.popup_opened == false)
            cart.popup = createPopup(cart.popup_id, 311, 200);

        cart.popup.innerHTML = '';
        cart.popup.innerHTML = $('was_added').innerHTML;
        //$('was_added').innerHTML = '';
        cart.timer_popup_close();
    },

    timer_popup_close : function(){

        //small hack
        var time_text = document.getElementsByName('timetext');
        time_text[1].innerHTML = 'До закрытия окна<br />' + cart.close_delay_secs + ' сек.';

        if(cart.close_delay_secs > 0) {
            cart.close_delay_secs -= 1;
            setTimeout(cart.timer_popup_close, 1000);

        } else {
            cart.close_delay_secs = 5;
            //alert (cart.close_delay_secs);
            cart.close_popup();
        }

    },

    close_popup : function(){

        document.body.removeChild(cart.popup);

    },

    recount : function(){
        var temp_array = document.getElementsByName('cart_item_count');
        var query_param = '';
        for(var i=0; i<temp_array.length;i++) {
            query_param += temp_array[i].id +'_' + temp_array[i].value;
            if(i+1 != temp_array.length)
                query_param += ",";
        }
        var url = '/cart/recount/'+query_param;
        document.location = url;
    },

    discount_calc : function()
    {
        var disc_number = $('user_discount').value;

        if(!disc_number) {
            //alert('no');
            //alert(cart.discount_calculated);
            if(cart.discount_calculated == true)
                cart.prices_restore();
        } else {
            if(disc_number<=999)
                if(disc_number.charAt(0)!='0') disc_number = '0' + disc_number;
            var url = '/rest_services/cart/discount_calc/'+ disc_number;
            rs.process(url, cart.prices_update);
        }
    },

    prices_update : function()
    {

        var data = rs.response;
        // alert( data ) ;
        if (data.discount == 'null') {
            if(cart.discount_calculated == false) {
                $('user_discount').style.color='#FF0000';
                $('user_discount').style.borderColor='#FF0000';
                $('user_discount').style.borderStyle='solid';
                $('user_discount').style.borderWidth='1px';
                $('user_discount').style.fontWeight = 'bold';
            // alert('Неправильный номер дисконтной карты.');

            } else {
                cart.prices_restore();
                $('user_discount').style.color='#FF0000';
                $('user_discount').style.borderColor='#FF0000';
                $('user_discount').style.borderStyle='solid';
                $('user_discount').style.borderWidth='1px'; //border-style:solid; border-width:1px;
                $('user_discount').style.fontWeight = 'bold';
            // alert('Неправильный номер дисконтной карты.');
            }
        } else {
            if(cart.discount_calculated == true) {
                $('user_discount').style.color='#FF0000';
                $('user_discount').style.borderColor='#FF0000';
                $('user_discount').style.borderStyle='solid';
                $('user_discount').style.borderWidth='1px';
                $('user_discount').style.fontWeight = 'bold';
                cart.prices_restore();
            }
            $('user_discount').style.color='#347C17';
            $('user_discount').style.borderColor='#347C17';
            $('user_discount').style.borderStyle='solid';
            $('user_discount').style.borderWidth='1px';
            $('user_discount').style.fontWeight = 'bold';
            cart.discount_value = data.discount;
            // alert(data.types_map);
            cart.types_map = data.types_map;
            var price_percentage = 0;
            var totalsum = 0;
            cart.netsum = 0;
            var spans = document.getElementsByTagName("span");

            for(var i=0; i<spans.length; i++) {

                if(spans[i].className == 'pr_f_c') {
                    var oldprice_s = spans[i].innerHTML;
                    // alert( oldprice_s );
                    oldprice = oldprice_s.replace(/[^0-9]/g, '') ;
                    var id = spans[i].id;
                    cart.base_prices[id] = oldprice ;
                    // alert(id);
                    // alert(cart.types_map[id]);
                    if(cart.types_map[id] == "IC_ORIGINAL" || cart.types_map[id] == "TC_ORIGINAL") {
                        price_percentage = 1 - 0.01 * parseInt(cart.discount_value);
                    // alert(price_percentage);
                    } else {
                        price_percentage = 1 - 0.02 * parseInt(cart.discount_value);
                    }
                    // alert(Math.ceil(((parseInt(oldprice) * price_percentage) / 100))  * 100);
                    spans[i].innerHTML = number_format(Math.round((Math.ceil(((parseInt(oldprice) * price_percentage) / 100)) * 100)/1000)*1000, 0,",","'");

                } else if(spans[i].className == 's_f_c') {
                    var oldsum_s = spans[i].innerHTML;
                    oldsum = oldsum_s.replace(/[^0-9]/g, '') ;
                    var id = spans[i].id;
                    cart.base_totals[id] = oldsum ;
                    if(cart.types_map[id] == "IC_ORIGINAL" || cart.types_map[id] == "TC_ORIGINAL")
                        price_percentage = 1 - 0.01 * cart.discount_value;
                    else
                        price_percentage = 1 - 0.02 * cart.discount_value;
                    // alert(Math.ceil((parseInt(oldsum) * price_percentage) / 100 ) * 100);
                    spans[i].innerHTML = number_format(Math.round((Math.ceil((parseInt(oldsum) * price_percentage) / 100 ) * 100)/1000)*1000,0,",","'");
                    totalsum += Math.round((Math.ceil(((parseInt(oldsum)*price_percentage)/100))  * 100)/1000)*1000;
                    cart.netsum += parseInt(oldsum);
                }
            }
            $('sum_without_delivery').innerHTML = number_format(totalsum,0,",","'");
            cart.delivery_change();
            $('helper_cart_sum').innerHTML = number_format(totalsum,0,",","'");
            cart.discount_calculated = true;
        }
    },

    delivery_change : function()
    {
        cart.delivery_type = $('delivery_change').options[$('delivery_change').selectedIndex].value;
        var oldsum_s = $('sum_without_delivery').innerHTML;
        var oldsum = parseInt(oldsum_s.replace(/[^0-9]/g, ''));
        var delivery_sum = 0;
        if(cart.netsum < 150000) {
            delivery_sum = 10000;
        } else if(cart.netsum >= 150000 && cart.netsum < 300000) {
            delivery_sum = 7000;
        } else if(cart.netsum >= 300000 && cart.netsum < 500000) {
            delivery_sum = 5000;
        } else if(cart.netsum >= 170000) {
            delivery_sum = 0;
        }
        $('sum_with_delivery').innerHTML = number_format(oldsum + delivery_sum,0,",","'");
        $('div_delivery_by').innerHTML = number_format(delivery_sum,0,",","'");
   /* 
		switch (cart.delivery_type) {
		case 'express':
				$('sum_with_delivery').innerHTML = number_format(netsum + 8000,0,",","'");
				$('div_delivery_by').innerHTML = number_format(8000,0,",","'");
				break;
		case 'selfdelivery':
				$('sum_with_delivery').innerHTML = number_format(cart.netsum,0,",","'");
				$('div_delivery_by').innerHTML = number_format(0,0,",","'");
				break;
		case 'courierw': case 'courier':
	      	  if(cart.netsum < 150000) {
        	       $('sum_with_delivery').innerHTML = number_format(cart.netsum + 10000,0,",","'") ;
			   $('div_delivery_by').innerHTML = number_format(10000,0,",","'");
             	   } else
    	 		if(cart.netsum >= 150000 && cart.netsum < 300000) {
    				$('sum_with_delivery').innerHTML = number_format(cart.netsum + 7000,0,",","'") ;
    				$('div_delivery_by').innerHTML =   number_format(7000,0,",","'"); }
    			else {
    				if(cart.netsum >= 300000 && cart.netsum < 500000) {
    					$('sum_with_delivery').innerHTML = number_format(cart.netsum + 5000,0,",","'") ;
    					$('div_delivery_by').innerHTML =  number_format(5000, 0, ",", "'");
				 } else {
    					$('sum_with_delivery').innerHTML = number_format(cart.netsum,0,",","'") ;
    					$('div_delivery_by').innerHTML = "0"; 
			         }
    			}
			break;

		case 'post':
				$('sum_with_delivery').innerHTML = number_format(parseInt(oldsum) + 16000,0,",","'") ;
				$('div_delivery_by').innerHTML = number_format(16000,0,",","'");
			break;
		}
     */       
    },

    prices_restore : function()
    {
        //alert('inside');
        var price_percentage = 0;
        var totalsum = 0;

        var spans = document.getElementsByTagName("span");

        for(var i=0; i<spans.length; i++) {
            if(spans[i].className == 'pr_f_c') {
                var id = spans[i].id;
                spans[i].innerHTML = number_format(parseInt(cart.base_prices[id]),0,",","'") ;
            } else if(spans[i].className == 's_f_c') {
                var id = spans[i].id;
                spans[i].innerHTML = number_format(parseInt(cart.base_totals[id]),0,",","'") ;
                totalsum+=parseInt(cart.base_totals[id]);
            }
        }
        cart.netsum = totalsum;
        $('sum_without_delivery').innerHTML = number_format(parseInt(totalsum),0,",","'");

        cart.delivery_type = $('delivery_change').options[$('delivery_change').selectedIndex].value;

        var delivery_sum = 0;
        if(cart.netsum < 150000) {
            delivery_sum = 10000;
        } else if(cart.netsum >= 150000 && cart.netsum < 300000) {
            delivery_sum = 7000;
        } else if(cart.netsum >= 300000 && cart.netsum < 500000) {
            delivery_sum = 5000;
        } else if(cart.netsum >= 500000) {
            delivery_sum = 0;
        }
        $('sum_with_delivery').innerHTML = number_format(totalsum + delivery_sum,0,",","'");
        $('div_delivery_by').innerHTML = number_format(delivery_sum,0,",","'");
/*        switch (cart.delivery_type) {
            case 'express':
                $('sum_with_delivery').innerHTML = number_format(totalsum + 6000,0,",","'");
                $('div_delivery_by').innerHTML = number_format(6000,0,",","'");
                break
            case 'courierw':
                if(totalsum < 150000) {
                    $('sum_with_delivery').innerHTML = number_format(totalsum + 5000,0,",","'") ;
                    $('div_delivery_by').innerHTML = number_format(5000,0,",","'");
                } else
                if(totalsum < 200000) { // 111
                    $('sum_with_delivery').innerHTML = number_format(totalsum + 3000,0,",","'") ;
                    $('div_delivery_by').innerHTML =   number_format(3000,0,",","'");
                }
                else {
                    if(totalsum >= 200000) {
                        $('sum_with_delivery').innerHTML = number_format(totalsum,0,",","'") ;
                        $('div_delivery_by').innerHTML =  '0';
                    }
                }
                break;

            case 'courier':
                if(totalsum<100000) {
                    $('sum_with_delivery').innerHTML = number_format(totalsum + 5000,0,",","'") ;
                    $('div_delivery_by').innerHTML = number_format(5000,0,",","'");
                } else
                if(totalsum<150000) {
                    $('sum_with_delivery').innerHTML = number_format(totalsum + 3000,0,",","'") ;
                    $('div_delivery_by').innerHTML = number_format(3000,0,",","'");
                }
                else {
                    if(totalsum >= 150000) {
                        $('sum_with_delivery').innerHTML = number_format(totalsum,0,",","'") ;
                        $('div_delivery_by').innerHTML = '0';
                    }
                }
                break;
            case 'post':
                $('sum_with_delivery').innerHTML = number_format(totalsum + 16000,0,",","'") ;
                $('div_delivery_by').innerHTML = number_format(16000,0,",","'");
                break;
        }*/

        $('helper_cart_sum').innerHTML = number_format(totalsum,0,",","'");
        cart.discount_calculated = false;
    },

    payment_type_change : function(event)
    {
        var elem = (window.getComputedStyle && !window.opera)? event.target : event.srcElement;
        var payment_type;

        if(elem.id == 'payment_type') {
            cart.payment_type = elem.options[elem.selectedIndex].value;
        } else {
            cart.payment_type = elem.id;
        }

        var select_payment = $('payment_type');

        switch(cart.payment_type) {
            case 'cash':
                $('cashless_form').style.display = 'none';
                $('cash_form').style.display = 'block';
                $('cash_td').className = 'ot4';
                $('cashless_td').className = 'ot5';
                $('cutter').src = '/img/ot_08.gif';
                for(var i=0, j=select_payment.length; i<j; i++) {
                    if(select_payment[i].value == cart.payment_type) {
                        select_payment.selectedIndex = i;
                    }
                }
                break;

            case 'cashless':
                $('cash_form').style.display = 'none';
                $('cashless_form').style.display = 'block';
                $('cash_td').className = 'ot5_1';
                $('cashless_td').className = 'ot4_1';
                $('cutter').src = '/img/ot_08_1.gif';

                for(var i=0, j=select_payment.length; i<j; i++) {
                    if(select_payment[i].value == cart.payment_type) {
                        select_payment.selectedIndex = i;
                    }
                }
                break;
        }

    },

    form_checker : function()
    {
        cart.payment_type = $('payment_type').options[$('payment_type').selectedIndex].value;
        var stop_sending = null;
        var organization_fields = ['cl_org_title', 'cl_org_address', 'cl_org_unp', 'cl_org_phones', 'cl_org_bank_account', 'cl_org_bank', 'cl_org_company_head', 'cl_org_work_reason'];
        switch(cart.payment_type){
            case 'cash':
                document.getElementsByName('user_name')[1].value = document.getElementsByName('user_name')[0].value;
                document.getElementsByName('user_phone')[1].value = document.getElementsByName('user_phone')[0].value;
                /* document.getElementsByName('user_discount')[1].value = document.getElementsByName('user_discount')[0].value; */
                document.getElementsByName('user_email')[1].value = document.getElementsByName('user_email')[0].value;
                document.getElementsByName('user_address')[1].value = document.getElementsByName('user_address')[0].value;

                if($('user_name').value == "") {
                    alert('Введите имя!');
                    stop_sending = 1;
                }
                if($('user_phone').value == "") {
                    alert('Введите номер телефона!')
                    stop_sending = 1;
                }
                break;

            case 'cashless':
                document.getElementsByName('user_name')[0].value = document.getElementsByName('user_name')[1].value;
                document.getElementsByName('user_phone')[0].value = document.getElementsByName('user_phone')[1].value;
                /*	document.getElementsByName('user_discount')[0].value = document.getElementsByName('user_discount')[1].value; */
                document.getElementsByName('user_email')[0].value = document.getElementsByName('user_email')[1].value;
                document.getElementsByName('user_address')[0].value = document.getElementsByName('user_address')[1].value;

                if($('user_name').value == "") {
                    alert('Укажите контактное лицо!');
                    stop_sending = 1;
                }

                if($('user_phone').value == "") {
                    alert('Введите номер телефона!');
                    stop_sending = 1;
                }

                if($('user_org_address').value == "") {
                    alert('Введите адрес доставки!');
                    stop_sending = 1;
                }

                for(var i=0, j=organization_fields.length; i<j; i++) {
                    if($(organization_fields[i]).value != "") {
                        break;
                        alert('Не полностью заполнены реквизиты предприятия');
                        stop_sending = 1;
                    }
                }
                break;

        }
        if(stop_sending == 1)
            return false;
        else
            saveuser11data();
        $('cart_form').submit();
    },

    error: function()
    {
    //alert('Error!');
    //remove_wait_for_div
    }

}


var highlighter = {

    pattern : null,
    focus_setted : null,
    //anchor_id: "uniq23sk6",


    highlight : function()
    {
        //var body = document.getElementsByTagName("body")[0];
        //var anchor = document.createElement( 'a' );
        //anchor.id = highlighter.anchor_id;
        //print_r(anchor, 'inline');
        highlighter.clear();
        highlighter.pattern = $('highlight_pattern').value;
        if(highlighter.pattern.length > 3)
            highlighter.pattern = highlighter.pattern.replace(/[^0-9]+/g,'');
        if(highlighter.pattern != '') {
            var spans = document.getElementsByTagName('span');
            for(var i=0, j=spans.length; i<j; i++) {
                if(spans[i].className == 'highlighted' || spans[i].className == 'non_highlighted') {
                    var model = spans[i].innerHTML;
                    model = model.toLowerCase();
                    highlighter.pattern = highlighter.pattern.toLowerCase();
                    if (model.indexOf(highlighter.pattern) >= 0 || model == highlighter.pattern){
                        spans[i].className = 'highlighted';
                        if(highlighter.focus_setted == null) {
                            //sprint_r(spans[i], 'inline');
                            var par = spans[i].parentNode;
                            par.focus();
                            //body.insertBefore(anchor, spans[i]);
                            highlighter.focus_setted = true;
                        }
                    }
                }

            }
        //print_r($("uniq23sk6"), 'inline');
        //	$(highlighter.anchor_id).focus();
        }
    },

    clear : function(){
        var spans = document.getElementsByTagName('span');
        if(highlighter.focus_setted != null) {
        //var par = $(highlighter.anchor_id).parentNode;
        //par.replaceChild($(highlighter.anchor_id));
        }
        highlighter.focus_setted = null;
        for(var i=0, j=spans.length; i<j; i++) {
            if(spans[i].className == 'highlighted' || spans[i].className == 'non_highlighted') {
                spans[i].className = 'non_highlighted';
            }
        }
    }
}

var searcher = {

    pattern : null,

    search : function()
    {
        searcher.pattern = $('partno_search_pattern').value;
        if(searcher.pattern.length < 2)
            alert('Слишком мало символов');
        else
            window.location.href = "/products/search/" + searcher.pattern;
    }
}

var scroll_manager = {

    y_top_limit : 200,
    y_bottom_limit: 400,
    block_height: null,
    current_y: null,
    current_scroll_y : null,


    scroll : function ()
    {

        //	if(navigator.appName.toLowerCase() !== 'microsoft internet explorer') {
        //	$('manager_block').style.position = 'fixed';
        //} else {

        if(window.location.href.indexOf('printer_brand') >= 0) {
            var diff = parseInt(document.documentElement.scrollTop) - scroll_manager.y_top_limit;
            var diff_top = document.documentElement.scrollTop - scroll_manager.y_top_limit;
            var lim_bottom = document.body.offsetHeight - scroll_manager.y_bottom_limit;

            var fdiv = document.getElementById('manager_block');
            if(document.documentElement.scrollTop + 300  > lim_bottom)
            {
                fdiv.style.bottom = 295 + "px";
            } else
            if(diff > 0) {
                fdiv.style.bottom = 0 + "px";
            // do nothing
            // fdiv.style.top = diff + "px";
            // $('manager_block').style.top = diff;
            } else {
                // alert( "DDD !!! ") ;
                fdiv.style.bottom = -165 + "px";
            }
        }
    }
}


var checkout = {
    checkout : function()
    {
        var order_number = $('checkout_field').value;
        window.location.href = "/orders/check/" + order_number;
    }
}


function sorry(elem)
{
    if (elem == 'paper')
        alert('Бумага появится в ближашее время, заходите позже, приносим извинения за неудобства');
    else if(elem == 'acces')
        alert('Акксессуары появятся в ближайшее время, заходите позже, приносим извинения за неудобства');
}

function find_cartridge()
{

    var search_str = $('search_field').value
    if (search_str.length < 2)
        alert('Слишком мало символов')
    else {
        href="?partno="+search_str;

        window.location ="index.php"+href;
    }

}

function isenter(event)
{
    if(event.keyCode == '13') {
        var obj = (window.getComputedStyle && !window.opera)? event.target : event.srcElement;
        switch(obj.name){

            case 'searcher':
                searcher.search();
                break;

            case 'highlighter':
                highlighter.highlight();
                break;

            case 'checkout':
                checkout.checkout();
                break;
        }
    }
}

function hookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.addEventListener)
    {
        element.addEventListener(eventName, callback, false);
    }
    else if(element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

function unhookEvent(element, eventName, callback)
{
    if(typeof(element) == "string")
        element = document.getElementById(element);
    if(element == null)
        return;
    if(element.removeEventListener)
        element.removeEventListener(eventName, callback, false);
    else if(element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function getEventTarget(e)
{
    e = e ? e : window.event;
    return e.target ? e.target : e.srcElement;
}

function cancelEvent(e)
{
    e = e ? e : window.event;
    if(e.stopPropagation)
        e.stopPropagation();
    if(e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

function SpinControlAcceleration(increment, milliseconds)
{
    increment = parseFloat(increment);
    if(isNaN(increment) || increment < 0)
        increment = 0;

    milliseconds = parseInt(milliseconds);
    if(isNaN(milliseconds) || milliseconds < 0)
        milliseconds = 0;

    this.GetIncrement = function()
    {
        return increment;
    }

    this.GetMilliseconds = function()
    {
        return milliseconds;
    }
}

function SpinControlAccelerationCollection()
{
    var _array = new Array();

    this.GetCount = function()
    {
        return _array.length;
    }

    this.GetIndex = function(index)
    {
        if(index < 0 || index >= _array.length)
            return null;

        return _array[index];
    }

    this.RemoveIndex = function(index)
    {
        if(index < 0 || index >= _array.length)
            return;

        newArray = new Array();
        for(var i=0; i<_array.length; i++)
        {
            if(i == index)
                continue;
            newArray.push(_array[i]);
        }
        _array = newArray;
    }

    this.Clear = function()
    {
        _array = new Array();
    }

    this.Add = function(spa)
    {
        if(spa.constructor != SpinControlAcceleration)
            return;

        if(_array.length == 0)
        {
            _array.push(spa);
            return;
        }

        var newSec = spa.GetMilliseconds();
        if(newSec > _array[_array.length-1].GetMilliseconds())
        {
            _array.push(spa);
            return;
        }

        var added = false;
        var newArray = new Array();
        var indexSec;
        for(var i=0; i<_array.length; i++)
        {
            if(added)
            {
                newArray.push(_array[i]);
            }
            else
            {
                indexSec = _array[i].GetMilliseconds();
                if(indexSec < newSec)
                {
                    newArray.push(_array[i]);
                }
                else if(indexSec == newSec)
                {
                    newArray.push(spa);
                    added = true;
                }
                else
                {
                    newArray.push(_array[i]);
                    newArray.push(spa);
                    added = true;
                }
            }
        }
        _array = newArray;
        return;
    }
}

function SpinControl( iid )
{
    var _this = this;

    var _accelerationCollection = new SpinControlAccelerationCollection();
    var _callbackArray = new Array();
    var _currentValue = 1;
    var _maximumVal = 100;
    var _minimumVal = 0;
    var _increment = 1;
    var _width = 50;

    var _running = 0;
    var _interval = -1;
    var _timeStart = 0;

    var _bodyEventHooked = false;

    var _container = document.createElement("DIV");
    _container.className = 'spinContainer';

    var _leftEdge = document.createElement("DIV");
    _leftEdge.className = 'spinLeftRightEdge';
    _leftEdge.style.left = '0px';

    var _bottomEdge = document.createElement("DIV");
    _bottomEdge.className = 'spinTopBottomEdge';
    _bottomEdge.style.top = '19px';

    var _topEdge = document.createElement("DIV");
    _topEdge.className = 'spinTopBottomEdge';
    _topEdge.style.top = '0px';

    var _rightEdge = document.createElement("DIV");
    _rightEdge.className = 'spinLeftRightEdge';
    _rightEdge.style.right = '0px';

    var _textBox = document.createElement("INPUT");
    _textBox.type = 'text';
    _textBox.className = 'spinInput';
    _textBox.value = _currentValue;
    _textBox.id = iid+'_count';
    _textBox.title= 'Попробуйте колесом на вашей мышке!';

    var _upButton = document.createElement("DIV");
    _upButton.className = 'spinUpBtn';
    _upButton.title= 'Попробуйте колесом на вашей мышке!';

    var _downButton = document.createElement("DIV");
    _downButton.className = 'spinDownBtn';
    _downButton.title= 'Попробуйте колесом на вашей мышке!';

    /*
   * Because IE 6 and lower don't support the transparent png background
   * mask that we use for the buttons.
   * So we use a regular old gif instead.
   * This means that, sadly, the button coloring does not work in IE6 and lower.
   */
    var canChangeBtnColors = true;
    if(document.body.filters)
    {
        var arVersion = navigator.appVersion.split("MSIE");
        var version = parseFloat(arVersion[1]);
        if(version < 7)
        {
            canChangeBtnColors = false;
            _downButton.style.backgroundImage = 'url(spin_control_buttons.gif)';
            _upButton.style.backgroundImage = 'url(spin_control_buttons.gif)';
            _downButton.style.backgroundColor = '#FFFFFF';
            _upButton.style.backgroundColor = '#FFFFFF';
        }
    }

    _container.appendChild(_leftEdge);
    _container.appendChild(_bottomEdge);
    _container.appendChild(_topEdge);
    _container.appendChild(_rightEdge);
    _container.appendChild(_textBox);
    _container.appendChild(_upButton);
    _container.appendChild(_downButton);

    function Run()
    {
        if(_running == 0)
            return;

        var elapsed = new Date().getTime() - _timeStart;
        var inc = _increment;

        if(_accelerationCollection.GetCount() != 0)
        {
            inc = 0;
            for(var i = 0; i<_accelerationCollection.GetCount(); i++)
            {
                if(elapsed < _accelerationCollection.GetIndex(i).GetMilliseconds())
                    break;

                inc = _accelerationCollection.GetIndex(i).GetIncrement();
            }
        }
        else if(elapsed < 600)
        {
            return;
        }
        DoChange( inc );

    }

    function CancelRunning()
    {
        _running = 0;
        if(_interval != -1)
        {
            clearInterval(_interval);
            _interval = -1;
        }
    }

    function DoChange(inc)
    {
        var newVal = _currentValue + inc * _running;
        UpdateCurrentValue(newVal);
    }

    function StartRunning(newState)
    {
        if(_running != 0)
            CancelRunning();

        _running = newState;

        DoChange(_increment);

        _timeStart = new Date().getTime();
        _interval = setInterval(Run, 150);
    }

    function UpdateCurrentValue(newVal)
    {
        if(newVal <_minimumVal)
            newVal = _minimumVal;
        if(newVal > _maximumVal)
            newVal = _maximumVal;

        newVal = Math.round(1000*newVal)/1000;

        _textBox.value = Math.round( newVal );
        if(newVal == _currentValue)
            return;

        _currentValue = newVal;

        for(var i=0; i<_callbackArray.length; i++)
            _callbackArray[i](_this, _currentValue);
    }

    function UpPress(e)
    {
        _upButton.className = 'spinUpBtnPress';
        _downButton.className = 'spinDownBtn';
        StartRunning(1);
        _textBox.focus();
        return cancelEvent(e);
    }

    function DownPress(e)
    {
        _upButton.className = 'spinUpBtn';
        _downButton.className = 'spinDownBtnPress';
        StartRunning(-1);
        _textBox.focus();
        return cancelEvent(e);
    }

    function UpHover(e)
    {
        if(!_bodyEventHooked)
            hookEvent(document.body, 'mouseover', ClearBtns);

        _upButton.className = 'spinUpBtnHover';
        _downButton.className = 'spinDownBtn';
        CancelRunning();
        return cancelEvent(e);
    }

    function DownHover(e)
    {
        if(!_bodyEventHooked)
            hookEvent(document.body, 'mouseover', ClearBtns);

        _upButton.className = 'spinUpBtn';
        _downButton.className = 'spinDownBtnHover';
        CancelRunning();
        return cancelEvent(e);
    }

    function ClearBtns(e)
    {
        var target = getEventTarget(e);
        if(target == _upButton || target == _downButton)
            return;
        _upButton.className = 'spinUpBtn';
        _downButton.className = 'spinDownBtn';
        CancelRunning();

        if(_bodyEventHooked)
        {
            unhookEvent(document.body, 'mouseover', ClearBtns);
            _bodyEventHooked = false;
        }
        return cancelEvent(e);
    }

    function BoxChange()
    {
        var val = parseFloat(_textBox.value);
        if(isNaN(val))
            val = _currentValue;

        UpdateCurrentValue(val);
    }

    function MouseWheel(e)
    {
        e = e ? e : window.event;
        var movement = e.detail ? e.detail / -3 : e.wheelDelta/120;
        UpdateCurrentValue(_currentValue + Math.round(_increment * movement));
        return cancelEvent(e);
    }

    function TextFocused(e)
    {
        hookEvent(window, 'DOMMouseScroll', MouseWheel);
        hookEvent(document, 'mousewheel', MouseWheel);
        return cancelEvent(e);
    }

    function TextBlur(e)
    {
        unhookEvent(window, 'DOMMouseScroll', MouseWheel);
        unhookEvent(document, 'mousewheel', MouseWheel);
        return cancelEvent(e);
    }

    this.StartListening = function()
    {
        hookEvent(_upButton, 'mousedown', UpPress);
        hookEvent(_upButton, 'mouseup', UpHover);
        hookEvent(_upButton, 'mouseover', UpHover);

        hookEvent(_downButton, 'mousedown', DownPress);
        hookEvent(_downButton, 'mouseup', DownHover);
        hookEvent(_downButton, 'mouseover', DownHover);

        hookEvent(_textBox, 'change', BoxChange);
        hookEvent(_textBox, 'focus', TextFocused);
        hookEvent(_textBox, 'blur', TextBlur);
    }

    this.StopListening = function()
    {
        unhookEvent(_upButton, 'mousedown', UpPress);
        unhookEvent(_upButton, 'mouseup', UpHover);
        unhookEvent(_upButton, 'mouseover', UpHover);

        unhookEvent(_downButton, 'mousedown', DownPress);
        unhookEvent(_downButton, 'mouseup', DownHover);
        unhookEvent(_downButton, 'mouseover', DownHover);

        unhookEvent(_textBox, 'change', BoxChange);
        unhookEvent(_textBox, 'focus', TextFocused);
        unhookEvent(_textBox, 'blur', TextBlur);

        if(_bodyEventHooked)
        {
            unhookEvent(document.body, 'mouseover', ClearBtns);
            _bodyEventHooked = false;
        }
    }

    this.SetMaxValue = function(value)
    {
        value = parseFloat(value);
        if(isNaN(value))
            value = 1;
        _maximumVal = value;

        UpdateCurrentValue(_currentValue);
    }

    this.SetMinValue = function(value)
    {
        value = parseFloat(value);
        if(isNaN(value))
            value = 0;
        _minimumVal = value;

        UpdateCurrentValue(_currentValue);
    }

    this.SetCurrentValue = function(value)
    {
        value = parseFloat(value);
        if(isNaN(value))
            value = 0;

        UpdateCurrentValue(value);
    }

    this.SetWidth = function(value)
    {
        value = parseInt(value);
        if(isNaN(value) || value < 25)
            value = 25;

        _width = value;

        _container.style.width = _width + 'px';
        _bottomEdge.style.width = (_width - 1) + 'px';
        _topEdge.style.width = (_width - 1) + 'px';
        _textBox.style.width = (_width - 20) + 'px';
    }

    this.SetIncrement = function(value)
    {
        value = parseFloat(value);
        if(isNaN(value))
            value = 0;
        if(value < 0)
            value = -value;

        _increment = value;
    }

    this.SetBackgroundColor = function(color)
    {
        _container.style.backgroundColor = color;
        _textBox.style.backgroundColor = color;
    }

    this.SetButtonColor = function(color)
    {
        if(!canChangeBtnColors)
            return;

        _upButton.style.backgroundColor = color;
        _downButton.style.backgroundColor = color;
    }

    this.SetFontColor = function(color)
    {
        _textBox.style.color = color;
    }

    this.SetBorderColor = function(color)
    {
        _topEdge.style.backgroundColor = color;
        _bottomEdge.style.backgroundColor = color;
        _leftEdge.style.backgroundColor = color;
        _rightEdge.style.backgroundColor = color;
    }

    this.AttachValueChangedListener = function(listener)
    {
        for(var i=0; i<_callbackArray.length; i++)
            if(_callbackArray[i] == listener)
                return;

        _callbackArray.push(listener);
    }

    this.DetachValueChangedListener = function(listener)
    {
        newArray = new Array();
        for(var i=0; i<_callbackArray.length; i++)
            if(_callbackArray[i] != listener)
                newArray.push(_callbackArray[i]);

        _callbackArray = newArray;
    }

    this.GetContainer = function()
    {
        return _container;
    }

    this.GetBox = function()
    {
        return _textBox;
    }

    this.GetCurrentValue = function()
    {
        return _currentValue;
    }

    this.GetMaxValue = function()
    {
        return _maximumVal;
    }

    this.GetMinValue = function()
    {
        return _minimumVal;
    }

    this.GetWidth = function()
    {
        return _width;
    }

    this.GetIncrement = function()
    {
        return _increment;
    }

    this.GetAccelerationCollection = function()
    {
        return _accelerationCollection;
    }

    _this.SetWidth(_width);
}

