var oxid = {
    // Search auto submit
    search : function(form, param) {
        var _form  = document.getElementById(form);
        var _param = document.getElementById(param);

        if( _form && _param && _param.value.length ) {
            _form.submit();
        }
    },

    // Popups
    popup: {
        load : function(){oxid.popup.setClass('wait','popup load on','on');},
        show : function(){oxid.popup.setClass('popup','popup on','on');},
        showFbMsg : function(){oxid.popup.setClass('popup','popup on fbMsg','on');},
        hide : function(id){oxid.popup.setClass(id?id:'popup','popup','');},

        setClass: function (id,pcl,mcl){
            var _mk = document.getElementById('mask');
            var _el = document.getElementById(id);
            if(_mk && _el) {
                _mk.className = mcl;
                _el.className = pcl;
            }
        },

        addShim : function(){
             var _mk = document.getElementById('mask');
             if(_mk) {_mk.appendChild(document.createElement('iframe'));}
        },

        open : function(url,w,h,r){
            if (url !== null && url.length > 0) {
                var _cfg = "status=yes,scrollbars=no,menubar=no,width="+w+",height="+h+(r?",resizable=yes":"");
                window.open(url, "_blank", _cfg);
            }
        },

        compare : function(url){
            oxid.popup.open(url,620,400,true);
        },

        zoom    : function(){
            oxid.popup.setClass('zoom','popup zoom on','on');
        },

        addResizer : function(image_id,container_id,pw,ph){
            var _el = document.getElementById(image_id);

            if(_el) {
                _el.onload = function(e){
                    if(this.tagName.toUpperCase() == 'IMG'){
                        oxid.popup.resize(container_id, this.width+pw, this.height+ph);
                    }
                };
            }
        },

        resize  : function(id, newWidth, newHeight ){

            if(newWidth === 0 && newHeight === 0){
                return;
            }

            var _el = document.getElementById(id);
            var maxWidth = newWidth;
            var maxHeight = maxHeight;

            if(_el) {
                if( typeof( window.innerWidth ) == 'number' ) {
                    maxWidth  = window.innerWidth;
                    maxHeight = window.innerHeight;
                } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                    maxWidth  = document.documentElement.clientWidth;
                    maxHeight = document.documentElement.clientHeight;
                }

                if(newWidth > maxWidth){newWidth = maxWidth;}
                if(newHeight > maxHeight){newHeight = maxHeight;}

                _el.style.width  = newWidth+30+'px';
                _el.style.height = newHeight+76+'px';

                _el.style.marginLeft = '-'+Math.round(newWidth/2)+'px';
                _el.style.marginTop  = '-'+Math.round(newHeight/2)+'px';
            }
        }

    },

    // Tags
    tags: {

        input  : null,

        select : function(e){
            oxid.tags.input.value += ' ' + this.innerHTML;
            this.className = 'sel';
            this.removeAttribute('onclick');
        },

        addSelect: function(id,input){
            var tg = document.getElementById(id);
            var ed = document.getElementById(input);
            if(tg && ed) {
                oxid.tags.input = ed;
                for (var i=0; i<tg.childNodes.length; i++) {
                    if(tg.childNodes[i].tagName && tg.childNodes[i].tagName.toUpperCase() == 'A'){
                       tg.childNodes[i].onclick = oxid.tags.select;
                       tg.childNodes[i].removeAttribute('href');
                    }
                }
            }
        }
    },

    // Forms
    form: {

        // send
        send: function(form) {
            var _form = document.forms[form];
            if(_form) {_form.submit();}
        },

        // submits form + changes cl and fnc values
        reload: function(stop,form,cl,fnc) {
            if(stop) {return;}
            var _form = document.forms[form];
            if(_form) {
                _form.elements.cl.value  = cl;
                _form.elements.fnc.value = fnc;
                _form.submit();
            }
        },

        // clears form values using given regex on fileld name
        clear: function(stop,form,pattern) {
            if(stop) {return;}
            var _fields = document.forms[form].elements, i;
            if(_fields) {
                for (i=0;i<_fields.length;i++) {
                    if( pattern.test(_fields[i].name) ) {
                        if( _fields[i].tagName.toUpperCase() === 'INPUT' ){_fields[i].value = "";}
                        if( _fields[i].tagName.toUpperCase() === 'SELECT'){_fields[i].item(0).selected = true;}
                    }
                }
            }
        },

        select: function(id,value) {
            var _el = document.getElementsByName(id);
            if(_el) {_el[value].checked='true';}
        }

    },

    // etc...
    showhide: function(id,show){
        var _el = document.getElementById(id);
        if (_el) {_el.style.display=show?'':'none';}
    },

    focus: function(id){
        var _el = document.getElementById(id);
        if (_el) {_el.focus();}
    },

    // switch image src
    image: function(id,src){
        var _el = document.getElementById(id);
        if( _el ) {_el.src=src;}
    },

    password: function(user_el,password_el,name) {
        var _u = document.getElementById(user_el);
        var _p = document.getElementById(password_el);
        if( _u ) {
            _u.focus();
            _p.style.display=(_u.value === name)?'none':'';
        }
    },

    checkAll: function(obj,pref) {
        if(document.getElementsByTagName){
            var inputs = document.getElementsByTagName("input");
            for (var i=0;i<inputs.length; i=i+1) {
                if(inputs[i].type == 'checkbox' && inputs[i].checked != obj.checked && pref == inputs[i].name.split('[')[0]){
                    inputs[i].checked = obj.checked;
                }
            }
        }
    }

};

function showReview()
{
    document.getElementById('write_review').style.display = 'block';
    document.getElementById('write_new_review').style.display = 'none';
    if (arguments.length == 1) {
        var oActForm = document.getElementById("rating");
        if ( oActForm !== null) {
            if (oActForm.artrating) {
                oActForm.artrating.value = arguments[0];
            } else if (oActForm.recommlistrating) {
                oActForm.recommlistrating.value = arguments[0];
            }
            var width = arguments[0] * 20;
            document.getElementById('current_rate').style.width = width + '%';
        }
    }
}

function setSellList( oInObj)
{
    //for module wlist
    var _wlist = document.getElementById("wlist");
    if ( _wlist !== null) {
        _wlist.href = _wlist.href + "&" + oInObj.name + "=" + oInObj.value;
    }
    //for original selectlist
    var _slist = document.getElementById("slist");
    if ( _slist !== null) {
        _slist.href = _slist.href + "&" + oInObj.name + "=" + oInObj.value;
    }
}


$(function (){
       curVal = $("#oxuser__oxusername").val();
       $("#oxuser__oxusername").focus(function(){
           if ($("#oxuser__oxusername").val() == curVal) {
               $(this).val('');
           }
       })
       $("#oxuser__oxusername").blur(function(){
       if ($.trim($(this).val()).length==0) {
               $(this).val(curVal);
           }
       })


        if($("#searchparam").val() == "") {
            $("#searchparam").val($("#searchparam").attr("title"));
        }

        $("#searchparam").focus(function(){
            if ($(this).val() == $(this).attr("title")){
                $(this).val('');
            }
        });
        $("#searchparam").blur(function(){
            if ($(this).val() == ''){
                $(this).val($(this).attr("title"));
            }
        });




       $("a.compareRemove").click(function(){
       $(this).closest("form").submit();
       });
       $(".ui-tabs-nav a").click(function(){
               return false;
       })

});

$(document).keydown( function( e ) {
   if( e.which == 27) {  // escape, close box
     oxid.popup.hide('zoom');
     $.unblockUI();
   }
});

function button_click(img_src) {
    var intGalleryId;
    $("#zoomed img").fadeOut("slow", function() {
        $("#loading").show();
        current_img = new Image();
        current_img.src = img_src;
        intGalleryId = setInterval(function() {
        if (current_img.complete) {
            clearTimeout(intGalleryId);
            $("#zoomed img").attr("src", img_src);
            $("#zoomed img").fadeIn("slow");
            $("#loading").hide();
        }

    }, 100);
    });
    }
$(document).ready(function() {
var gallery_index = 0;
var gallery_total = $("#zoomTabs a").size();

    $('#subPics a').click(function() {
        $("#zoomTabs").css({"left":"0"});
        gallery_index = 0;
        $.blockUI({message: $('#zoomUI')});

        $('.blockOverlay').click(function() {
            oxid.popup.hide('zoom');
            $.unblockUI();
        });

        button_click($("img", this).attr("longdesc"));
        $("#gallery-prev").css({"visibility":"hidden"});
        if($("#zoomTabs a").size() > 5){
            $("#gallery-next").css({"visibility":"visible"});
        }
        return false;
    });
    $("#zoomTabs").css({"width": $("#zoomTabs a").size() * 92});
    $('#zoomUI a.close').click(function() {
        $.unblockUI();
        return false;
    });

    $("#zoomTabs a:first").addClass("active");
       $("#zoomTabs a").click(function(){
               button_click($(this).attr("href"));
           $("#zoomTabs a").removeClass("active");
           $(this).addClass("active");
           return false;
       });


$("#gallery-next").click(function(){
    $("#navArea ul").animate({left: '-=92px'}, "slow");
    gallery_index += 1;
    checkNav();
});

$("#gallery-prev").click(function(){
    $("#navArea ul").animate({left: '+=92px'}, "slow");
    gallery_index -= 1;
    checkNav();
});

function checkNav() {
    if (gallery_index == 0) {
        $("#gallery-prev").css({"visibility":"hidden"});
    }else{
        $("#gallery-prev").css({"visibility":"visible"});
    }

    if(gallery_index == gallery_total - 5) {
        $("#gallery-next").css({"visibility":"hidden"});
    }else{
        $("#gallery-next").css({"visibility":"visible"});
    }
}



    var fabPaddingTop = 500 - $('#productInfo').height();
    if (fabPaddingTop > 0) {
        $('#productInfo').css({'padding-top': fabPaddingTop * 0.3 + 'px'});
    }

   if ($("ul#shopMenu").length > 0) {
       $(".oneCat").parent("ul").addClass("oneCategoryBlock");
       $('ul#shopMenu li ul li ul').hide(); //for ie
       $('ul#shopMenu li ul').hide();
       $(".topbask ul").show();

       $("ul#shopMenu li.products .withnextmenu").hover(function(){
        getPrevEl = $(this).parent("li").prevAll().size();
        setVposition = ($(".nav_submenu li").height()+1) * getPrevEl;
        $(this).next("ul").css("top",setVposition);
       })

        var config = {
            sensitivity: 3,
            over: makeshow,
            timeout: 100,
            out: makehide
        };

        if ($('ul#shopMenu li.products,ul#shopMenu li.products li').size()) {
            $('ul#shopMenu li.products,ul#shopMenu li.products li').hoverIntent(config);
        }
   }

    function listenHide(){
        if($(".nav_submenu").is(":hidden")){
            $('a#catTree').removeClass("hoverOn");
        }
    }
    function makeshow() {
         if (intBasketOpen) basket_close();
         if (intCompareOpen) compare_close();
         $('a#catTree').addClass("hoverOn");
         $(this).children('ul:first').show();
    }
    function makehide(e){
        $(this).children('ul:first').hide();
        listenHide();
    };

    $(".listView .actions").each(function(){
        iHeight = $(this).parents("li").height() - 8;
        $(this).css({"height":iHeight + "px"});
    });
    $("#search_refine").change(function(){
        window.location = $(this).val();
    });


    $("#basket_panel").hover(
       function () {
           $("#fnCart a").addClass("active");
       },
       function () {
           $("#fnCart a").removeClass("active");
       }
     );


    getCompareLeftPosition = $("#fnCompare").offset().left;
    getCompareTopPosition = $("#fnCompare").offset().top;
    getCompareHeadHeight = $("#fnCompare").height();
    getCompareHeadWidth = $("#fnCompare").width();

    getCartLeftPosition = $("#fnCart").offset().left;
    getCartTopPosition = $("#fnCart").offset().top;
    getCartHeadHeight = $("#fnCart").height();
    getCartHeadWidth = $("#fnCart").width();


    $("#compare_panel").css({"left": getCompareLeftPosition + getCompareHeadWidth +2, "top":getCompareTopPosition + getCompareHeadHeight});
    $("#basket_panel").css({"left": getCartLeftPosition + getCartHeadWidth+2, "top":getCartTopPosition + getCartHeadHeight});


    var cartSpotlightItem;
    $("a.external").attr("target","_blank");

    var timeout;

    $("#fnCompare,#compare_panel").hover(function(){
        if($("#compare_panel").is(":hidden")){
            clearTimeout(compare_timer);
            ajax_tocompare('fnc=tocomparelist');
        }else{
         clearTimeout(timeout);
         clearTimeout(compare_timer);
        }
    },function(){
        if ($("#compare_panel").is(":visible")) {
            timeout = setTimeout(function(){
            compare_close();
            }, 100);
        }
    });

    $("#fnCart,#basket_panel").hover(function(){
        if($("#basket_panel").is(":hidden")){

            $.ajax({
                type: "POST",
                url: selfActionLink,
                data: "cl=ajaxfnc&fnc=getbasketinfo",
                success: function(msg){
                     $("#cartCount").empty();
                     $("#cartCount").append(msg);

                     if ( parseFloat(msg) != 0 ) {
                         basket_open();
                     }
                }
              });
        }else{
         clearTimeout(timeout);
         clearTimeout(cart_timer);
        }
    },function(){
        if ($("#basket_panel").is(":visible")) {
            timeout = setTimeout(function(){
                basket_close();
            }, 100);
        }
    });



    $("a.closeitem_button").click(function(){
        $(this).parents("tr").next("tr").toggle();
        $(this).toggleClass("expand");
        return false;
    });
    $("a.getTo").anchorAnimate();

    if ($(".oLayer").length > 0) {
        $(".oLayer").colorbox({width:"50%", maxHeight:'80%'});
    }

    if ($(".oLayerIframe").length > 0) {
        $(".oLayerIframe").colorbox({width:"700px", height:'470px', iframe:false, scrolling:false});
    }

    if ($("a.oLayerIframe2").length > 0) {
        $("a.oLayerIframe2").colorbox({width:"700px", height:'450px', iframe:true, scrolling:false});
    }

    $('.innerLabel').focus(function() {
        if (this.value == this.defaultValue){
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });

    $('.innerLabel').blur(function() {
        if ($.trim($(this).val()).length==0) {
            this.value = (this.defaultValue);
        }
    });

    // has IE7 compatibility issue...
    if ($("#topAsusCategories").size()) {
           $("#topAsusCategories").carouFredSel({
               items: 3,
               prev: "#next",
               next: "#prev",
               circular: false,
               infinite: false,
               auto: false,
               direction: "up",
               scroll: 1
           });
    };

    $('img.swap').hover(function () {
       tmp_src = $(this).attr('src');
       if ($(this).attr('oversrc')) {
              $(this).attr('src', $(this).attr('oversrc'));
       }

    }, function () {
       $(this).attr('src',tmp_src);
    });



});

var intBasketTimerId;
var intBasketOpen;
var intCompareTimerId;
var intCompareOpen;

var compare_timer;
var cart_timer;


function basket_close() {
    $("#fnCart a.trigger").children("span").removeClass("showFnContent");
    $("#basket_panel").hide();
}
function basket_open(){
    compare_close();
    $("#fnCart a.trigger").children("span").addClass("showFnContent");
    $("#basket_panel").show();
}
function ajax_tobasket(data){
    cart_timer = setTimeout(function(){
        basket_close();
    }, 5000);
    $.ajax({
       type: "POST",
       url: selfActionLink,
       data: "cl=ajaxfnc&"+data,
       success: function(msg){
            basket_open();
            $("#basket_content").empty();
            $("#basket_content").append(msg);
            getBasketInfo();
            if(typeof addToCartGA == 'function') {addToCartGA();}
       }
     });
    var blNewProduct = data[3];
    if ( blNewProduct ) {
        $("#basket_panel").removeClass("empty");
        $("#fnCart").removeClass("empty");
        $("#basket_panel").addClass("full");
        $("#fnCart").addClass("full");
    }
}
function getBasketInfo(){
    $.ajax({
       type: "POST",
       url: selfActionLink,
       data: "cl=ajaxfnc&fnc=getbasketinfo",
       success: function(msg){
            $("#cartCount").empty();
            $("#cartCount").append(msg);

            if ( parseFloat(msg) == 0 ) {
                $("#basket_panel").removeClass("full");
                $("#fnCart").removeClass("full");
                $("#basket_panel").addClass("empty");
                $("#fnCart").addClass("empty");
                basket_close();
            }
       }
     });
}

function compare_close() {
    $("#fnCompare a.trigger").children("span").removeClass("showFnContent");
    $("#compare_panel").hide();
}

function compare_open(){
    basket_close();
    $("#fnCompare a.trigger").children("span").addClass("showFnContent");
    $("#compare_panel").show();
}

function ajax_tocompare(data, aid){
    compare_timer = setTimeout(function(){
        compare_close();
    }, 5000);
    $.ajax({
       type: "POST",
       url: selfActionLink,
       data: "cl=ajaxfnc&"+data,
       success: function(msg){
            compare_open();
            $("#compare_content").empty();
            $("#compare_content").append(msg);
            getCompareInfo();
            if ($('#compare_overflow').length==0){
                $('#add_compare_'+aid).toggle();
                $('#rem_compare_'+aid).toggle();
            }
       }
     });
}
function getCompareInfo(){
    $.ajax({
       type: "POST",
       url: selfActionLink,
       data: "cl=ajaxfnc&fnc=getcompareinfo",
       success: function(msg){
            $("#compareCount").empty();
            $("#compareCount").append(msg);
       }
     });
}

jQuery.fn.anchorAnimate = function(settings) {
     settings = jQuery.extend({
        speed : 700,
        onComplete: function() {}
    }, settings);

    return this.each(function(){
        var caller = this
        $(caller).click(function (event) {
            event.preventDefault()
            var locationHref = window.location.href
            var elementClick = $(caller).attr("href")

            var destination = $(elementClick).offset().top;
            $("html:not(:animated),body:not(:animated)").animate({scrollTop: destination}, settings.speed, function() {
                window.location.hash = elementClick
            });
              return false;
        })
    })
}


function showDrop(e){
    hideDrop();
    sublist = $(this).next("ul.dropbox");
    valWidth = $(this).outerWidth();

    if(sublist.outerWidth() < valWidth){
    sublist.css("width", (valWidth-2)+'px');
    }

    if (sublist.length) {
        sublist.toggle("fast");
        $(this).toggleClass("selected");
    }
    e.stopImmediatePropagation();
}
function hideDrop(){
    $("ul.dropbox").hide();
    $("div.textDrop p").removeClass("selected");
}

$(function() {
    $("div.textDrop p").click(showDrop);

    $(document).click( function(e){
        if(e.target.className !== ".textDrop" && e.target.className !== "textDrop" && e.target.parentNode.className !== "textDrop"){
          $(".dropbox").hide();
        }
      }
    );

    $("div.textDrop p").hover(function(){
       $(this).toggleClass("selected");
    }, function(){
       $(this).toggleClass("selected");
    });
});

$(function(){
    $('#bargainForm').submit(function() {
    $('#bargainFormResponse').html('');
    $.ajax({
        type: "POST",
        url: '/index.php',
        data: $(this).serialize(),
        dataType: "json",
        success: function(resp){
            if( resp.msg ) {
                if( resp.saved==1 ) {
                    $('#bargainForm').hide();
                    $('#bargainFormResponse').css('color', '#3C3B3B');
                } else {
                    $('#bargainFormResponse').css('color', 'red');
                }
                $('#bargainFormResponse').html(resp.msg);
            }
        }
     });
    return false;
  });
});


$(function(){
    $('#prodrequestForm').submit(function() {
    $('#prodrequestFormResponse').html('');
    $.ajax({
        type: "POST",
        url: '/index.php',
        data: $(this).serialize(),
        dataType: "json",
        success: function(resp){
            if( resp.msg ) {
                if( resp.saved==1 ) {
                    $('#prodrequestForm').hide();
                    $('.prodrequestDescr').hide();
                    $('.prodrequestFormTitle').hide();
                    $('#prodrequestFormResponse').css('color', '#3C3B3B');
                } else {
                    $('#prodrequestFormResponse').css('color', 'red');
                }
                $('#prodrequestFormResponse').html(resp.msg);
            }
        }
     });
    return false;
  });
});

//==============================================================================
// Filter form
//==============================================================================
(function($){

    /**
     * Binds function to object
     */
    function bind( fn, obj ){
        return function(){
            fn.apply(obj, arguments);
        };
    }
    /**
     * Provides activity layer for whole window
     * @constructor
     */
    function ActivityLayer(){}
    /**
     * @type {jQueryObject}
     */
    ActivityLayer.prototype.layer = null;
    /**
     * @type {boolean}
     */
    ActivityLayer.prototype.state = false;
    /**
     * @type {jQueryObject}
     */
    ActivityLayer.prototype.container = null;
    /**
     * @return {jQueryObject}
     */
    ActivityLayer.prototype.getLayer = function(){
        if(!this.layer){
            this.container = $( "body" );
            this.layer = $( "<div/>" ).addClass( "activity" ).css({
                "opacity" : 0.5,
                "backgroundColor" : "#ffffff",
                "position" : "absolute",
                "zIndex" : 100,
                "width" : "100%",
                "height" : "100%",
                "display" : "none",
                "cursor" : "wait",
                "left" : 0,
                "top" : 0
            }).appendTo( this.container );
        }
        return this.layer;
    };
    /**
     * Starts activity
     */
    ActivityLayer.prototype.start = function(){
        if(!this.state){
            this.getLayer().show().height( this.container.height() );
            this.state = true;
        }
    };
    /**
     * Stops activity
     */
    ActivityLayer.prototype.stop = function(){
        if(this.state){
            this.getLayer().hide();
            this.state = false;
        }
    };
    
    /**
     * Provides filter form behavior
     * @param {jQueryObject} form
     * @constructor
     */
    function FilterForm(form){
        if(!form.length){
            return;
        }
        if(!form.hasClass(this.handledClass)){
            return;
        }
        this.form = form;
        this.getInputs()
            .bind( "change.FilterForm",bind(this.submitFilter,this));
        this.form.find( "a.clear-filter" )
            .bind( "click.FilterForm", bind( this.onClearFilterLinkClick, this ) );
    }
    /**
     * @const {string}
     */
    FilterForm.prototype.handledClass = "category-filter";
    /**
     * @type {form}
     */
    FilterForm.prototype.form = null;
    /**
     * @type {jQueryObject}
     */
    FilterForm.prototype.inputs = null;
    /**
     * @type {boolean}
     */
    FilterForm.prototype.active = true;
    /**
     * Submits filter
     */
    FilterForm.prototype.submitFilter = function(){
        if( !this.active ){
            return;
        }
        this.active = false;
        var layer = new ActivityLayer();
        layer.start();
        this.form.submit();
    };
    /**
     * @return {jQueryObject}
     */
    FilterForm.prototype.getInputs = function(){
        if( !this.inputs ){
            this.inputs = this.form.find( "input[type=checkbox]" );
        }
        return this.inputs;
    };
    /**
     * Clears specific filter
     * @param {string=} filterName
     */
    FilterForm.prototype.clearFilter = function(filterName){
        var inputs = this.getInputs();
        for (var i = inputs.length - 1; i >= 0; --i){
            if( (!filterName || filterName == inputs[ i ].name) && inputs[ i ].checked ){
                inputs[ i ].checked = false;
            }
        }
        this.submitFilter();
    };
    /**
     * Event listener
     * @param {jQuery.event} event
     */
    FilterForm.prototype.onClearFilterLinkClick = function( event ){
        if( event.target.id ){
            this.clearFilter( event.target.id.replace( "clear-", "" ) + "[]" )
        } else {
            this.clearFilter();
        }
    };
    /**
     * @type {FilterForm}
     */
    var handle = null;
    /**
     * Behavior starter
     */
    $( document ).bind( "ready", function(){
        handle = new FilterForm( $( "#filters" ) );
    });
    
    //==========================================================================
    // Fields validation module
    //==========================================================================
    
    /**
     * @param {jQueryObject} field
     * @param {Function} validator
     * @constructor
     */
    function FieldValidator(field,validator){
        this.field = field;
        if( !field.length ){
            this.validator = function(){
                return '';
            };
            return;
        }
        this.validator = validator;
        this.field.bind( "keyup.FieldValidator", bind( this.clearError, this ) );
    }
    /**
     * @type {jQueryObject}
     */
    FieldValidator.prototype.field = null;
    /**
     * @type {jQueryObject}
     */
    FieldValidator.prototype.validator = null;
    /**
     * @type {string}
     */
    FieldValidator.prototype.errorMessage = "";
    /**
     * Revalidate item
     */
    FieldValidator.prototype.revalidate = function(){
        this.errorMessage = this.validator(this.field[0].value);
        this.updateState();
    };
    /**
     * Updates state
     */
    FieldValidator.prototype.updateState = function(){
        if( this.errorMessage ){
            this.field.addClass( "error-field" );
        } else {
            this.field.removeClass( "error-field" );
        }
    };
    /**
     * Clears error
     */
    FieldValidator.prototype.clearError = function(){
        if( this.errorMessage ){
            this.errorMessage = "";
            this.updateState();
            this.onErrorClear_ && this.onErrorClear_();
        }
    };
    
    /**
     * @constructor
     * @param {jQueryObject} button
     * @param {Object} validators
     * @param {jQueryObject=} errorBox
     */
    function ButtonClickValidator( button, validators, errorBox ){
        if( button.length ){
            this.button = button.bind( "click.ButtonClickValidator", bind( this.onButtonClick, this ) );
            this.errorBox = errorBox;
            this.validators = [];
            this.clearErrorBox = bind( this.clearErrorBox, this );
            for (var v in validators) {
                var validator = new FieldValidator( $( v ), validators[ v ].call() );
                this.validators.push( validator );
                validator.onErrorClear_ = this.clearErrorBox;
            }
        }
    }
    /**
     * @type {jQueryObject}
     */
    ButtonClickValidator.prototype.button = null;
    /**
     * @type {jQueryObject}
     */
    ButtonClickValidator.prototype.errorBox = null;
    /**
     * @type {jQueryObject}
     */
    ButtonClickValidator.prototype.errorBox = null;
    /**
     * @type {Array.<FieldValidator>}
     */
    ButtonClickValidator.prototype.validators = null;
    /**
     * Event listener
     * @param {jQuery.event} event
     */
    ButtonClickValidator.prototype.onButtonClick = function( event ){
        var errors = [];
        for (var i = this.validators.length - 1; i >= 0; --i) {
            this.validators[ i ].revalidate();
            if( this.validators[ i ].errorMessage ){
                errors.push( this.validators[ i ].errorMessage );
            }
        }
        if( errors.length ){
            event.preventDefault();
            event.stopPropagation();
            if( this.errorBox && this.errorBox.length ){
                this.errorBox[ 0 ].innerHTML = errors.join( "<br/>" );
                this.errorBox.show();
            }
        }
    };
    /**
     * Clears error box
     */
    ButtonClickValidator.prototype.clearErrorBox = function(){
        if( this.errorBox && this.errorBox.length ){
            this.errorBox[ 0 ].innerHTML = "";
            this.errorBox.hide();
        }
    };
    
    var validatorsConfig = {
        "#pay" : {
            "#edit-init-sum-input" : function(){
                var offset = parseFloat( $( "#edit-ordersum" )[ 0 ].value );
                if( isNaN( offset ) ){
                    offset = 10000;
                }
                return function( value ){
                    value = parseInt(value);
                    if(isNaN(value)){
                        return "Įvesta neleistina suma, leidžiami tik sveikieji skaičiai";
                    }
                    if( value >= offset ){
                        return "Įvesta neleistinai didelė suma";
                    }
                    if( value < 0 ){
                        return "Įvesta neteisinga suma";
                    }
                    return "";
                };
            }
        }
    };
    
    $( document ).bind("ready",function(){
        var errorBox = $( "#errorbox" );
        var h = [], b = null;
        for (var v in validatorsConfig) {
            b = $( v );
            if( b.length ){
                h.push(new ButtonClickValidator(b, validatorsConfig[ v ], errorBox));
            }
        }
    });

})(jQuery);

