$(document).ready(
    function()
    {
        jQuery.fn.centerScreen = function(loaded)
        {
        var obj = this;
            if(!loaded)
            {
                obj.css('top', $(window).height()/2-this.height()/2);
                obj.css('left', $(window).width()/2-this.width()/2);
                $(window).resize(function(){ obj.centerScreen(!loaded); });
            }
            else
            {
                obj.stop();
                obj.animate(
                    {
                        top: $(window).height() / 2 - this.height()/2,
                        left: $(window).width() / 2 - this.width() / 2
                    },
                    200,
                    'linear'
                );
            }
        }
    }
);

var lensTypeSwitch = false;
var lensBrandSwitch = false;

function blurLoginLabels()
{
    $('#login input').each(function(index, input){
        if ($(input).val().length > 0)
        {
            $(input).prev("label").css('display','none');
        }
    });
}

function prepareLoginForm()
{
    $('#login input').focus(function(){$(this).prev("label").css('display','none');});
    $('#login input').blur(function(){
        setTimeout(blurLoginLabels, 500);
    });

    $('#login input').blur();

    $('#login a.login').click(function(){
        if ($('#login').hasClass('open'))
        {
            $('#login').removeClass('open');
        }
        else
        {
            $('#login').addClass('open');
        }
        return false;
    });
}

function prepareSearchForm()
{
    if ($.browser.msie && $.browser.version == '7.0')
    {
        $('#keyword').focus(function(){$(this).prev("label").css('display','none');});
        $('#keyword').blur(function(){if ($(this).val().length <= 0){$(this).prev("label").css('display','block');}});
        $('#extended').click(function(){
            $('#search').addClass('extended');
            $('#search .close, #search #keyword').css('display', 'block');
            if ($('#search #keyword').val().length <= 0)
            {
                $('#search label').css('display', 'block');
            }
        });
        $('#search div a.close').click(function(){
            $('#search').removeClass('extended');
            $('#search .close, #search #keyword, #search label').css('display', 'none');
            $('#keyword').val('');
            return false;
        });
    }
    else
    {
        $('#keyword').focus(function(){$(this).prev("label").css('display','none');});
        $('#keyword').blur(function(){if ($(this).val().length <= 0){$(this).prev("label").css('display','block');}});
        $('#extended').click(function(){
            $('#search').addClass('extended');
            $('#search .close, #search #keyword').css('display', 'block');
            if ($('#keyword').val().length < 1)
            {
                $('#search label').css('display', 'block');
            }
        });
        $('#search div a.close').click(function(){
            $('#search').removeClass('extended');
            $('#search .close, #search #keyword, #search label').css('display', 'none');
            $('#keyword').val('');
            return false;
        });
    }
}

function prepareOrderHistory()
{
    $('#orderhistory td.last a').click(function(){
        table = $(this).parent().parent().parent().next('tr.even').children('td').children('table').get(0);
        if ($(table).css('display') == 'none')
        {
            $(table).css('display', 'block');
            $(this).addClass('open');
        }
        else
        {
            $(table).css('display', 'none');
            $(this).removeClass('open');
        }
    });

    $('#orderhistory #content > table table').css('display', 'none');
    $('#orderhistory tr.odd a').removeClass('open');
    $('#ordersperpage').change(function(){this.form.submit()});

    $('#orderhistory tr.odd td[class!=last] a').click(function(){
        table = $(this).parent().parent().next('tr.even').children('td').children('table').get(0);
        if ($(table).css('display') == 'none')
        {
            $(table).css('display', 'block');
            $(this).parent().parent().children('.last').children('div').children('a').addClass('open');
        }
        else
        {
            $(table).css('display', 'none');
            $(this).parent().parent().children('.last').children('div').children('a').removeClass('open');
        }
    });

    if ($('#orderhistory #content > table table tbody td').length > 0)
    {
        $('#orderhistory #content > table table').tablesorter({
            sortList: [[3,1]],
            cssAsc: 'up',
            cssDesc: 'down',
            cssHeader: 'header'
        });
    }
}

function prepareBasket()
{

    $('#basketForm').submit(function(){
        $('input:disabled').removeAttr('disabled');
    });
    if ($('#basket #content > table tbody td').length > 0)
    {
        $('#basket #content > table').tablesorter({
            sortList: [[2,0]],
            textExtraction: function(node) {
                if ($(node).children('input').length > 0)
                {
               		return $('input', $(node)).val();
                }
                else
                {
                    return $(node).text();
                }
            },
            cssAsc: 'up',
            cssDesc: 'down',
            cssHeader: 'header'
        });
        $('#basket #content > table thead a').removeAttr('href');
    }

    var oldValue = 0;

    $('#basket .qty').focus(function(){
        oldValue = $(this).val();
    });

    $('#basket .qty').blur(function(){
        if (/^[0-9]+$/.test($(this).val()))
        {
            oldValue = $(this).val();
            var binput = this;
            $.ajax({
                type: 'POST',
                url: config[3] + '/basket/add',
                dataType: 'json',
                data: $(this).serialize(),
                success: function(data){
                    $('span', $(binput).parent().siblings('.total')).text(parseFloat(data).toFixed(2));
                    $('input', $(binput).parent().siblings('.total')).val(parseFloat(data).toFixed(2));
                    recountBasket();
                }
            });

            if ($(this).val() == 0)
            {
                $(this).parent().parent().remove();
            }
        }
        else
        {
            alert('Only decimals allowed!');
            $(this).val(oldValue);
        }
    });

    $('#basket table input[type="checkbox"]').click(function(){
        if ($(this).is(':checked'))
        {
            $('#tbon').text((parseFloat($('#tbon').text()) - parseFloat($(this).parent().prev().text())).toFixed(2));
            $('input.qty', $(this).parent().parent()).attr('disabled', 'disabled');
        }
        else
        {
            $('#tbon').text((parseFloat($('#tbon').text()) + parseFloat($(this).parent().prev().text())).toFixed(2));
            $('input.qty', $(this).parent().parent()).removeAttr('disabled');
        }
        recountBasket();
    });

    $('#basket .qty').keypress(function(e){
        if (e.which == 13) return false;
    });
}

function init()
{
    $('#singleproduct .product form dl dd').each(function(index, dd){
        $(dd).height($(dd).prev().height());
    });

    prepareLoginForm();
    prepareSearchForm();

    if ($('form dl dd.hint').length > 0)
    {
        $('#wrapper').append('<div id="description" style="display: none;"></div>');
        $('form dl dd.hint').each(function(){
            i = $('<i class="hint">Hint</i>');
			
            i.click(function(){
                if ($('#description').is('.' + $(this).parent().get(0).id) && ($('#description').css('display') == 'block'))
                {
                    $('#description').css('display', 'none');
                }
                else
                {
                    offset = $(this).offset();
                    $('#description').css('display', 'block').attr('class', $(this).parent().get(0).id).html($(this).parent().next('.hint').html());
                    $('#description').css('top', offset.top).css('left', offset.left - 120);
                }
            });
            $(this).prev().append(i);
            $(this).hide();
        });
    }

    $('#catalogue > ul > li > a').append('<i />');
    $('#catalogue > ul > li > a').click(function(){

    $('#catalogue li').removeClass('open');
    $('#catalogue li').removeClass('lastopen');

        if ($(this).siblings('ul').length > 0)
        {
            if ($(this).parent().is('.open'))
            {
                //$(this).parent().removeClass('open');
            }
            else
            {
                $(this).parent().addClass('open');
            }
            return false;
        }
    });

    $('#catalogue ul.lenstypes li:first-child').addClass('first');
    $('#catalogue ul.lenstypes li:last-child').addClass('last');
    $('#catalogue > ul > li > ul > li').hover(
        function(){if ($(this).children('div').length > 0){$(this).addClass('hover');}},
        function(){$(this).removeClass('hover');}
    );

    $('.product a[rel="popup"]').lightBox({
        imageLoading: config[2] + '/img/lightbox-ico-loading.gif',
        imageBtnClose: config[2] + '/img/lightbox-btn-close.gif',
        imageBtnPrev: config[2] + '/img/lightbox-btn-prev.gif',
        imageBtnNext: config[2] + '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: '',
        txtOf: ''
    });
    $('.product a[rel="colour"]').lightBox({
        imageLoading: config[2] + '/img/lightbox-ico-loading.gif',
        imageBtnClose: config[2] + '/img/lightbox-btn-close.gif',
        imageBtnPrev: config[2] + '/img/lightbox-btn-prev.gif',
        imageBtnNext: config[2] + '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: '',
        txtOf: ''
    });
    $('.packages-product-image a[rel="product1"]').lightBox({
        imageLoading: config[2] + '/img/lightbox-ico-loading.gif',
        imageBtnClose: config[2] + '/img/lightbox-btn-close.gif',
        imageBtnPrev: config[2] + '/img/lightbox-btn-prev.gif',
        imageBtnNext: config[2] + '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: '',
        txtOf: ''
    });
    $('.packages-product-image a[rel="product2"]').lightBox({
        imageLoading: config[2] + '/img/lightbox-ico-loading.gif',
        imageBtnClose: config[2] + '/img/lightbox-btn-close.gif',
        imageBtnPrev: config[2] + '/img/lightbox-btn-prev.gif',
        imageBtnNext: config[2] + '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: '',
        txtOf: ''
    });	
    $('.packages-product-image a[rel="product3"]').lightBox({
        imageLoading: config[2] + '/img/lightbox-ico-loading.gif',
        imageBtnClose: config[2] + '/img/lightbox-btn-close.gif',
        imageBtnPrev: config[2] + '/img/lightbox-btn-prev.gif',
        imageBtnNext: config[2] + '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: '',
        txtOf: ''
    });		

    $('#productlist > li').hover(
        function(){$(this).addClass('hover');},
        function(){$(this).removeClass('hover');}
    );

    if ($('#productlist .description').length > 0)
    {
        $('#wrapper').append('<div id="description"></div>');
    }

    $('#productlist .info').click(function()
	{ 
        if ($('#description').is('.' + $(this).parent().parent().parent().get(0).id) && ($('#description').css('display') == 'block'))
        {
            $('#description').css('display', 'none');
        }
        else
        {
            offset = $(this).offset();
            $('#description').css('display', 'block').attr('class', $(this).parent().parent().parent().get(0).id).html($(this).parent().parent().children('.description').html());
            $('#description').css('top', offset.top).css('left', offset.left - 120);
        }
    });

    $('.faq > li > strong > a').click(
        function(){
        if ($(this).parent().parent().siblings('.open').length > 0)
        {
            $('.faq > li').removeClass('open');
            $(this).parent().parent().addClass('open');
        }
        else if ($(this).parent().parent().is('.open'))
        {
            $(this).parent().parent().removeClass('open');
        }
        else
        {
            $(this).parent().parent().addClass('open');
        }
    });

    prepareOrderHistory();

    prepareBasket();

    $('#manufacturer_catalogue table').each(function(index, table){
        /*
         * $(table).tablesorter({ sortList: [[2,0]], headers: { 1: { sorter:
         * false }, 3: { sorter: false } }, cssAsc: 'up', cssDesc: 'down',
         * cssHeader: 'header' });
         */
    });

    $('#welcome h3').css('cursor', 'pointer').click(function(){
        if ($('#welcome').hasClass('closed'))
        {
            $('#welcome').removeClass('closed');
        }
        else
        {
            $('#welcome').addClass('closed');
        }
    });
    function kaadeeljmanirjaalabocitucilveekupieljautaaskljuudas(pointer){
        pointer.parent().parent().children('.active').removeClass('active');
        pointer.parent().addClass('active');
        pointer.parent().next('.even').addClass('active');
    }
    $('#vision_exam td.clicky').click(function(){
        kaadeeljmanirjaalabocitucilveekupieljautaaskljuudas($(this));
    });
    $('#vision_exam #content > form > table > tbody > tr.odd:not(.empty) > td').filter('[class!="first"]').click(function(){
        /*alert(1);
        $(this).parent().parent().children('.active').removeClass('active');
        $(this).parent().addClass('active');
        $(this).parent().next('.even').addClass('active');*/
        kaadeeljmanirjaalabocitucilveekupieljautaaskljuudas($(this));
    });
    $('#vision_exam #content > form > table > tbody > tr.odd:not(.empty) > td').filter('[class=="first"]').click(function(){


    });
    $('#vision_exam #content > form > table > tbody > tr.odd a.close').click(function(){
    $(".aaaaaSARKANS").removeClass("aaaaaSARKANS").css("background","");
        $(this).parent().parent().removeClass('active');
        $('#popup').css('display', 'none');
        $(this).parent().parent().next('.even').removeClass('active');
    });
    $('#vision_exam #content > form > table > tbody > tr.odd a.next').click(function(){
        if ($(this).parent().parent().next('.even').next('.odd:not(.empty)').length > 0)
        {
            $('#popup').css('display', 'none');
            $(this).parent().parent().removeClass('active');
            $(this).parent().parent().next('.even').removeClass('active');
            $(this).parent().parent().next('.even').next('.odd').addClass('active');
            $(this).parent().parent().next('.even').next('.odd').next('.even').addClass('active');
        }
    });
    $('#vision_exam #content > form > table > tbody > tr.odd a.previous').click(function(){
        if ($(this).parent().parent().prev('.even').prev('.odd:not(.empty)').length > 0)
        {
            $('#popup').css('display', 'none');
            $(this).parent().parent().removeClass('active');
            $(this).parent().parent().next('.even').removeClass('active');
            $(this).parent().parent().prev('.even').prev('.odd').addClass('active');
            $(this).parent().parent().prev('.even').addClass('active');
        }
    });
    $('#vision_exam #popup a.close').click(function(){$('#popup').css('display','none');});
    $('#vision_exam #popup').css('display', 'none');
    $('#vision_exam .filters select').change(function(){
        $('#popup').remove();
        setTimeout(function(){$('#vision_exam .filters select').get(0).form.submit();}, 100);
    });
    var offytoffy = 520;
    //if ((screen.width>=1024) && (screen.height>=768)) {offytoffy = 640;}
    offytoffy = (screen.width/2)-$('#popup').width()/2- 210;
    $('#vision_exam a.reservation').click(function(){
        offset = $(this).offset();
        $(".aaaaaSARKANS").removeClass("aaaaaSARKANS").css("background","");
        $(this).addClass("aaaaaSARKANS").css("background","#8b0003");
        $('#popup').css('display', 'block').css('top', offset.top - 329).css('left', /*offset.left -*/ offytoffy);
        $('#reda').val($(this).attr('href'));
        return false;
    });

    $('#vision_exam #optometrer_submit').click(function(){
        $('#vision_exam dd span.error').each(function(i, span){
            $(span).parent().remove();
        });
        error = false;

        if (!/^(\S+|\S+\s\S+)$/.test($('#fname').val()))
        {
            $('#fname').parent().after('<dd><span class="error">' + i18n[0] + '</span></dd>');
            error = true;
        }
        if (!/^(\S+|\S+\s\S+)$/.test($('#lname').val()))
        {
            $('#lname').parent().after('<dd><span class="error">' + i18n[0] + '</span></dd>');
            error = true;
        }
        if (!/^[0-9\(\)\-\+ ]+$/.test($('#rphone').val()))
        {
            $('#rphone').parent().after('<dd><span class="error">' + i18n[0] + '</span></dd>');
            error = true;
        }
        //if (!/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test($('#remail').val()))
        if(!/^([a-zA-Z0-9_\.\-])+\@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test($('#remail').val()))
        {
            $('#remail').parent().after('<dd><span class="error">' + i18n[0] + '</span></dd>');
            error = true;
        }
        return !error;
    });

    $('a.sendtoafriend').toggle(
        function(){
            offset = $(this).position();
            $('form.sendtoafriend > div').css('display', 'block').css('top', offset.top + $(this).height()).css('left', offset.left + 1);
        },
        function(){
            $('form.sendtoafriend > div').css('display', 'none');
        }
    );

    $('#register_link').click(function(){
        $(this).attr('href', $(this).attr('href') + '?' + $('form').serialize());
    });

    $('#paymenttype').change(function(){
        $('#checkout .pt').css('display', 'none');
        $('#checkout .pt' + this.value).css('display', 'block');
        if (this.value == 4)
        {
            $('#bank').change();
        }
    });

    $('#bank').change(function(){
        parentY = $(this).parent().parent();
        elList = [$('dt + dd.checkbox', parentY), $('dt + dd.notice', parentY)];

        coefficient = ($(this).val() == 1) ? 1 : 0;

        elList[1 - coefficient].show();
        elList[1 - coefficient].prev().show();
        elList[0 + coefficient].hide();
        elList[0 + coefficient].prev().hide();
    });
    $('#bank').change();

    $('#backorder').change(function(){
        $('#backorderHint').text(this.options[this.selectedIndex].title);
    });

    $('#use_shipment').click(function(){
        if ($(this).is(':checked'))
        {
            $('#checkout option.ns').css('display', 'block');
        }
        else
        {
            $('#checkout .ns').css('display', 'none');
            $('#paymenttype').get(0).selectedIndex = 0;
            $('#paymenttype').change();
        }
    });

    $('#checkout .pt').css('display', 'none');
    $('#checkout .pt' + $('#paymenttype').val()).css('display', 'block');

    $('#checkout').submit(function(){
        if ($('#paymenttype').val() == 8 && $('#insurancepolicy').val().length <= 0)
        {
            alert(i18n[0]);
            $('#insurancepolicy').focus();
            return false;
        }
    });

    $('#reminder h3 a').click(function(){
        if ($(this).is('.active'))
        {
            $(this).parent().next('div').css('display', 'block');
            $(this).removeClass('active');
        }
        else
        {
            $(this).parent().next('div').css('display', 'none');
            $(this).addClass('active');
        }
    });
    $('#reminder h3 a').click();

    $('#lenstype').change(function(){


    if($(this).val() == 0){
    $("#lensmanufacturer").val(0);
    $(this).val(0)
    searchForm(false, true, $('#lensmanufacturer').val(), $('#lenstype'), true);
    searchLiquids(false, true, $('#lensmanufacturer').val(), $('#lenstype').val());
    }else{
    $("#lensmanufacturer").val(0);
    searchForm(true, false, $('#lensmanufacturer').val(), $('#lenstype').val());
    }

        if (this.selectedIndex > 0){
             $('#liquidname').attr("disabled","disabled");
        }else{
                 $('#liquidname').attr("disabled","");
        }

    });

    $('#lensmanufacturer').change(function(){
    searchForm(false, true, $('#lensmanufacturer').val(), $('#lenstype').val());
    searchLiquids(false, true, $('#lensmanufacturer').val(), $('#lenstype').val());
    /*
        if(this.selectedIndex > 0){
             $('#liquidname').attr("disabled","disabled");
        }else{
                        if($('#lenstype').val() < 1){
             				$('#liquidname').attr("disabled","");
                 		}
        }
    */
    });

    $('#lensname').change(function(){
        if (this.selectedIndex > 0)
        {
            window.location = this.value;
        }
        });

    $('#liquidname').change(function(){
        if (this.selectedIndex > 0)
        {
            window.location = this.value;
        }

    });
    /*
    $('#liquidname').change(function(){
        if (this.selectedIndex > 0)
        {
            window.location = this.value;
        }
        });
    */

    $('#contacts #popup').hide();
    $('#roadmap').click(function(){
        $('#popup').css('top', (parseInt($(this).offset().top) - 500) + 'px').show();
        $('#branch').val($(this).parent().attr('id').substr(6)).change();
        return false;
    });
    $('#contacts #popup a.close').click(function(){
        $('#popup').hide();
        return false;
    });
    $('#branch').change(function(){
        $('#map').attr('src', config[1] + '/branches/' + $(this).val() + '_thumb.jpg');
        $('#popup h4').text($('option[value="' + $(this).val() + '"]', this).attr('title'));
        $('#popup div.description').html($('#branch' + $(this).val() + ' div.description').html());
    });
    /*
     * $('#contacts .vcard').css('cursor',
     * 'pointer').filter('[id!="1"]').click(function(){ $('#popup').css('top',
     * (parseInt($(this).offset().top) - 500) + 'px').show();
     * $('#branch').val(this.id).change(); });
     */
    $('#branchlist .odd, #branchlist .even').css('cursor', 'pointer').click(function(){
        $('#popup').css('top', (parseInt($(this).offset().top) - 500) + 'px').show();
        $('#branch').val($('.vcard', $(this)).attr('id').substr(6)).change();
    });

    $('form.registration dl dd > span.error').each(function(index, span){
        $(span).parent().css('height', '4em');
        $(span).parent().prev('dt').css('height', '4em');
    });
}

$(window).load(function(){
    $('.section .aside:has(img)').each(function(index, img){
        if ($(img).height() > $(img).parent().height())
        {
            $(img).parent().height($(img).height());
        }
    });
});

function searchForm(manufacturer, category, mIndex, cIndex, repeated, changeVal)
{
    var manufacturer = typeof(manufacturer) == 'boolean' ? manufacturer : true;
    var category = typeof(category) == 'boolean' ? category : true;
    var repeated = typeof(repeated) == 'boolean' ? repeated : true;
    var changeVal = typeof(changeVal) == 'boolean' ? changeVal : true;

    $.ajax({
        type: 'POST',
        url: config[0],
        dataType: 'json',
        data: $('#search').serialize(),
        success: function(data){


                if(repeated == true && category == true && $('#lenstype').val() == 0){

                //$('#lensmanufacturer').val(0);


                if(data.Manufacturers.length === undefined){
                //if($('#lenstype').val() > 0){
                $('#lensmanufacturer option[value!=0]').remove();
              $.each(data.Manufacturers, function(key, value){
              $('#lensmanufacturer').append('<option value="' + key + '">' +
              value + '</option>'); });
                //}
                }

                if(data.LensCategories === undefined){
                $('#lenstype option[value!=0]').remove();
                }else{
                $('#lenstype option[value!=0]').remove();
              $.each(data.LensCategories, function(key, value){
              $('#lenstype').append('<option value="' + key + '">' + value + '</option>');
              });
                }

                }else{

                if(manufacturer == true && $('#lenstype').val() == 0){
                /*$('#lensmanufacturer option[value!="0"]').remove();
              $.each(data.Manufacturers, function(key, value){
              $('#lensmanufacturer').append('<option value="' + key + '">' +
              value + '</option>'); });
                */
                }else{
                if(data.Manufacturers.length === undefined){
                $('#lensmanufacturer option[value!=0]').remove();
              $.each(data.Manufacturers, function(key, value){
              $('#lensmanufacturer').append('<option value="' + key + '">' +
              value + '</option>'); });
                }

                if(data.LensCategories.length === undefined){
              $('#lenstype option[value!=0]').remove();
              $.each(data.LensCategories, function(key, value){
              $('#lenstype').append('<option value="' + key + '">' + value + '</option>');
              });
                }

                }

                }

            $("#lensname").attr("disabled","disabled");

            $('#lensname option[value!=0]').remove();
            if(data.Lenses.length === undefined){
            $.each(data.Lenses, function(key, value){
                $('#lensname').append('<option value="' + key + '">' + value + '</option>');
            });
            }


            if($("#lensname option").size()-1 > 0){
            $("#lensname").attr("disabled","");
            }

            if(changeVal != false){
            $('#lensmanufacturer').val(mIndex);
            $('#lenstype').val(cIndex);
            }
        }
    });
}

function searchLiquids(manufacturer, category, mIndex, cIndex)
{
    var manufacturer = typeof(manufacturer) == 'boolean' ? manufacturer : true;
    var category = typeof(category) == 'boolean' ? category : true;

    $.ajax({
        type: 'POST',
        url: config[0]+'/liquids',
        dataType: 'json',
        data: $('#search').serialize(),
        success: function(data){
            $('#liquidname option[value!=0]').remove();

            $("#liquidname").attr("disabled","disabled");
            if(data.Liquids.length === undefined){
            $.each(data.Liquids, function(key, value){
                $('#liquidname').append('<option value="' + key + '">' + value + '</option>');
            });
            }

            if($("#liquidname option").size()-1 > 0){
            $("#liquidname").attr("disabled","");
            }



            $('#lensmanufacturer').val(mIndex);
        }
    });
}

$(init);

function validateEmail(field)
{
    if (/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($(field).val()))
    {
        return true;
    }
    else
    {
        alert(i18n[1]);
        $(field).focus();
        return false;
    }
}

function recountBasket()
{
    var count = 0;
    var total = 0;
    var due = 0;

    $('#basket #content table input[type="text"]').each(function(index, input){
        count += parseFloat($(input).val());
    });
    $('#basket #content table .total span').each(function(index, cell){
        total += parseFloat($(cell).text());
    });
    due = total;
    $('#basket #content table input:checked').each(function(index, input){
        due -= parseFloat($(input).parent().siblings('.total').text());
    });

    $('#tqty, #bqty').text(count);
    $('#tprice').text(total.toFixed(2));
    $('#tpay, #bprice').text(due.toFixed(2));

    var balance = parseFloat($('#tbon').text());

    $('#basket table input[type="checkbox"]').each(function(i, check){
        price = parseFloat($(check).parent().prev().text());

        if (price > balance && !($('.qty', $(check).parent().parent()).is(':disabled')))
        {
            $(check).attr('disabled', 'disabled');
        }
        else
        {
            $(check).removeAttr('disabled');
        }
    });

    if ($('#basket #content table .qty').length == 0)
    {
        $('.continuation button').hide();
        $('.continuation p').show();
    }
}

function bonusTotal()
{
    var bonus = 0.0;

    $('#basket table input:checked').each(function(i, check){
        bonus += parseFloat($('.total input[type="hidden"]', $(check).parent().parent()).val());
    });

    return bonus;
}

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}

function oc_add(a,b)
{
    o = []
    for(var i=0;i<a.length;i++){
        o[i] = a[i];
    }
    for(var i=0;i<b.length;i++){
        k = a.length+i;
        o[k] = b[i];
    }
    return o;
}

function registerAuctionHit(productName,linkToFollow,newWindow){
newWindow = typeof(newWindow) != 'undefined' ? newWindow : false;

$.ajax({
   type: "GET",
   url: "../../../logAuction.php",
   data: "product="+productName,
     success: function() {
     /*console.log(linkToFollow);*/
     if(newWindow == true){
     window.open(linkToFollow);
     }else{
     window.location = linkToFollow;
     }
     }
     });


}


function lenseQuantityCheck(side)
{
    var color = $("#goooPoo"+side).val();
    var sideQuantity = $("#quantity"+side);
    var removeMe = $(".ableToRemove"+side);
    var pwr = $("#power_"+side).val();
    var twoLensMinimum = false;
    var sixLensMinimum = false;

    oc0 = [];
    oc1 = ['143','144','145','150','154','155']; // ADORE minimums 2 kraasas
    oc2 = ['135','136','137','138','139','140','141','142','146','147','148','149','151','153']; // ADORE minimums 4 kraasas
    oc3 = ['127','128','129']; //  SOFTCOLOR minimums 6 kraasas

    if( color in oc(oc1) && parseFloat(pwr) > 0 )
    {
        ocz = oc_add (oc1,oc2);
    }
    else if ( color in oc(oc3) && parseFloat(pwr) > 0 )
    {
        ocz = oc_add (oc0,oc3);
    }
    else if (color == '128')
    {
        ocz = oc_add (oc0,oc3);
    }
    else
    {
        ocz = oc2;
    }

//if(color in oc(['135','136','137','138','139','140','141','142','146','147','148','149','151','152','153'])){


if(color in oc(ocz))
{
removeMe.each(function()
{
    if( color in oc(oc1) )
    {
        twoLensMinimum = true;

        if($(this).val() < 2)
        {
            $(this).attr("disabled","disabled");
        }
    }
    else if ( color in oc(oc3) )
    {
        sixLensMinimum = true;

        if($(this).val() < 6)
        {
            $(this).attr("disabled","disabled");
        }
    }
    else
    {
        $(this).attr("disabled","disabled");
    }
});
    if(twoLensMinimum)
    {
        $(".minimum2"+side).attr("selected","selected");
    }
    else if (sixLensMinimum)
    {
        $(".minimum6"+side).attr("selected","selected");
    }
    else
    {
        $(".minimum"+side).attr("selected","selected");
    }
}
else
{
    removeMe.each(function()
    {
        $(this).attr("disabled","");
    });
$(".minNormal"+side).attr("selected","selected");
}

}


