$.fn.clearDefault = function(){
    return this.each(function(){
        var defaultValue = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == defaultValue) $(this).val("");
        });
        $(this).blur(function(){
            if ($(this).val() == "") $(this).val(defaultValue);
        });
    });
};


function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

function pad( number, length ) {
    var str = '' + number;
    while (str.length < length) { str = '0' + str; }
    return str;
}

jQuery.fn.equalHeight = function () {
    var height        = 0;
    var maxHeight    = 0;

    // Store the tallest element's height
    this.each(function () {
        height        = jQuery(this).outerHeight();
        maxHeight    = (height > maxHeight) ? height : maxHeight;
    });

    // Set element's min-height to tallest element's height
    return this.each(function () {
        var t            = jQuery(this);
        var minHeight    = maxHeight - (t.outerHeight() - t.height());
        var property    = jQuery.browser.msie && jQuery.browser.version < 7 ? 'height' : 'min-height';

        t.css(property, minHeight + 'px');
    });
};



$(document).ready(function() {
function popMenu(){
    var oViewport = $(window).height();
    if ($(".subCategoriesLayer").length) {
        $(".root.has.exp > a").hoverIntent({
            over: function(){
                targetEl = $(this).parent("li");
                if (!targetEl.hasClass("act")) {
                    var sub = $(".subCategoriesLayer", targetEl);
                    var targetElHeight = targetEl.height() + 7;
                    var y_ElPositionTop = targetEl.position().top + targetElHeight;

                    var subHeight = sub.innerHeight();
                    var dimTop = targetEl.offset().top - $(window).scrollTop();
                    var dimBottom = oViewport - (dimTop + targetElHeight);
                    if (subHeight > y_ElPositionTop) {
                        if (subHeight > dimTop && dimTop < targetEl.position().top) {
                            sub.css("top", "-" + dimTop + "px");
                        }
                        else {
                            sub.css("top", "-" + targetEl.position().top - 15 + "px");
                        }
                    }
                    else
                        if (subHeight > dimBottom) {
                            var trueHeight = subHeight + 4;
                            var posCorrection = trueHeight - targetElHeight - dimBottom + 5;
                            if (posCorrection > 10) {
                                sub.css("top", "-" + posCorrection + "px");
                            }
                        }
                    targetEl.addClass("act");
                    var newHeight = $(this).outerHeight();
                    targetEl.children(".connector").css({
                        "height": newHeight + parseInt(correctPos) + "px",
                        "background": "#fff"
                    }).show();
                    
                }
            },
            interval: 300,
            out: function(){

            }
        });

        $(".root.has.exp").hoverIntent({
            timeout: 400,

            over: function(){

            },
            out: function(){
                targetEl = $(this);
                if (targetEl.hasClass("act")) {
                    targetEl.removeClass("act");
                }
                targetEl.children(".connector").hide();
            }
        });
    }
}

    $("#basket-form th span").equalHeight();

    $(".external").attr("target", "_blank");

    var msgCookie = 'msgstatus';
    if (getCookie(msgCookie) != '1') {
        setCookie(msgCookie);
    }

    $(".dismiss").click(function(){
        $("#versionNote").fadeOut("slow", function(){
            $(this).remove();
        });
        setCookie(msgCookie, 1);
    });


    $("#basketExpander").click(function(e){
        $('#basket').toggleClass("expanded", "collapsed");
        if($(this).hasClass("collapsed")){
            $(this).removeClass("collapsed")
        }else{
            $(this).addClass("collapsed")
        }
    });

    $(".tipsIcons").mouseenter(function(e){
        $(this).addClass("on");
    });
    $(".tipsIcons").mouseleave(function(e){
        $(this).removeClass("on");
    });

    $(".basketTipsIcons").mouseenter(function(e){
        $(this).addClass("on");
    });
    $(".basketTipsIcons").mouseleave(function(e){
        $(this).removeClass("on");
    });

    $("#blankSaveBox input[type=text]").clearDefault();

    $(".termsconfirm a").click(function(){
       return false;
    });

    $("#catsLink a").click(function(event){
        event.preventDefault(event);
        if ($("#treeSubCats").is(":visible")) {
            $("#treeRootCats").slideDown('fast', function(){
                $("#treeSubCats").hide();
            });
        } else {
            if ( $.browser.msie && parseInt($.browser.version, 10) == 7 ) {
                $("#treeRootCats").slideUp('fast', function () {
                    $('#treeSubCats').show();
                });
            } else {
                $("#treeRootCats").slideUp('fast');
                $('#treeSubCats').show();
            }
        }
    });

    $("input.amount").keyup(function(e){
        if($(this).attr("value") == 0){
            $(this).removeClass("active");
        }else if($(this).attr("value") > 0){
            $(this).addClass("active");
        }
    });

    $(".tabContent").hide();
    $($(".tabs .act a").attr("href")).show();
    $(".tabs a").click(function(e){
        e.preventDefault();
        if(!$(this).hasClass("act")){
            $(".tabs li").removeClass("act");
            $(this).parent("li").addClass("act");
            $(".tabContent").hide();
            $($(this).attr("href")).show();
        }
    });

    //tvirtinamu uzsakymu komentarai
    $(".orderComment").focus(function(e){$(this).addClass("expanded");});
    $(".orderComment").blur(function(e){$(this).removeClass("expanded");});

    $('.level1li').hoverIntent(
            {
                over: function() { $(this).addClass('level1li_hover'); },
                timeout: 100,
                interval: 100,
                out: function() { $(this).removeClass('level1li_hover'); }
            }
        );

    if ( $.browser.msie && parseInt($.browser.version, 10) == 7 ) {
        var correctPos = "-2";
    }else if ( $.browser.msie && parseInt($.browser.version, 10) < 9 ) {
        var correctPos = "0";
    }else{
        var correctPos = "0";
    }
    popMenu();
    $(window).resize(function(){
        popMenu();
    });

    //kalendorius
    if($( ".withCalendar" ).length){
        $( ".withCalendar" ).datepicker({
                showOn: "button",
                firstDay: 1,
                constrainInput: true,
                buttonImage: "out/officeday/img/calendar-icon.png",
                buttonImageOnly: true,
                dateFormat: "yy-mm-dd",
                minDate: startDeliv,
                  beforeShowDay: function(date) {
                    id = date.getFullYear()+pad(date.getMonth()+1,2)+pad(date.getDate(),2);

                    if (daysCache[id]==1 || (daysCache[id]!=0 && (date.getDay()==6 || date.getDay()==0) ))
                        return [0];
                    else
                        return [1];
                }
        });
    }
    
    // Clendar for stats page, note that calendar in stat page use different 
    // options, so javascript can not be reused
    if($( ".stat_withCalendar" ).length){
        $( ".stat_withCalendar" ).datepicker({
                showOn: "button",
                firstDay: 1,
                constrainInput: true,
                buttonImage: "out/officeday/img/calendar-icon.png",
                buttonImageOnly: true,
                dateFormat: "yy-mm-dd",
                minDate: '2005-01-01',
                maxDate: '2015-12-31'
        });
    }
});

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function saveBlankItem(sType)
{
    var sHtml = '';

    if(sType == 'same')
    {
        $(".tobasketform").each(function() {
            amount = $(this).find('.amount').val();
            blankItemId = $(this).find('input[name=blankItemId]').val();
            sHtml = sHtml + '<input type="hidden" name="am['+blankItemId+']" value="'+amount+'" /><br/>'
        });
        $('#hidenvaluessame').html(sHtml)
        $('#sameForm').submit();
    }

    if(sType == 'new')
    {
        sHtml = '';

        $(".tobasketform").each(function() {
            amount = $(this).find('.amount').val();
            artId = $(this).find('input[name=blankItemId]').val();
            sHtml = sHtml + '<input type="hidden" name="am['+artId+']" value="'+amount+'" /><br/>'
        });

        $('#hidenvalues').html(sHtml)
        $('#newBlank').show();
    }
}


