if (typeof(Sputnik) == "undefined") // setting up global namespace for singleton
    var Sputnik = {};

Sputnik.Utils = {
    equalBlocksAdjusting: function() {
      var height = 0;
      $(".payment .payment-block.equal").each(function(){
        var currentHeight = $(this).outerHeight();
        if ( height < currentHeight ) {height = currentHeight;}
      });
      $(".payment .payment-block.equal").css("min-height", height);
    },
    center: function (elem) {
        var w = $(window);
        var e = $(elem);
        e.css({"position":"absolute"});
        e.css({"top": (w.height()-e.height())/2+w.scrollTop()});
        e.css({"left": (w.width()-e.width())/2+w.scrollLeft()});
        return e;
    }, // center
    findPos: function(elem){ // http://www.quirksmode.org/js/findpos.html
        var curleft = curtop = 0;
        if (elem.offsetParent) {
            do {
                curleft += elem.offsetLeft;
                curtop += elem.offsetTop;
                } while (elem = elem.offsetParent);
        } // if
        return [curleft,curtop];
    }, // findPos

    halfHeight: function(){
        var all_half = $(".item.half, .about.half, .subscribe.half");
        all_half.each(function(e){
            if ((e+1) % 2 != 0) {
                this_height = $(all_half[e]);
                that_height = $(all_half[e+1]);
                if ( this_height.height() > that_height.height() ) {
                    that_height.height(this_height.height());
                    } // if
                }
                else {
                    this_height.height(that_height.height());
                    }
            }); // each
    }, // halfHeight

    formatCurrency: function(strValue){
      strValue = strValue.toString().replace(/\$|\,/g,'');
      dblValue = parseFloat(strValue);

      blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
      dblValue = Math.floor(dblValue*100+0.50000000001);
      intCents = dblValue%100;
      strCents = intCents.toString();
      dblValue = Math.floor(dblValue/100).toString();
      if(intCents<10)
        strCents = "0" + strCents;
      for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
        dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
        dblValue.substring(dblValue.length-(4*i+3));
      return ('$' + ((blnSign)?'':'-') + dblValue + '.' + strCents);
    },

    adjustImageWidth: function(image_selector, width){
      var image = $(image_selector);
      var newImg = new Image();
      newImg.src = image.attr('src');
      newImg.onload = function(){
        image.css({'width' : this.width < width ? this.width : width});
      }
    },

    prepareErrorMessage: function(){
      // move div.flash outside content
      if ($('div.flash div').size() != 0) message_container = $('div.flash');
      if (typeof(message_container) != 'undefined') {
        $('div.flash').remove();
        $('body').append(message_container);
        message_container.removeAttr('style').attr('style', 'display: block');
      }
    },

    showErrorMessage: function(){
      // Show ... and then hide Flash message
      if ($('div.flash div').size() != 0) {
        $('div.flash .errorExplanation').show();
        $("div.flash").slideDown(1500);
        setTimeout("jQuery('div.flash').fadeOut(1500)",10000);
      }
    }

} // utils

Sputnik.PopUp = {
    init: function () {
        $(".pop-prod ul li").hover(
            function () {$(this).addClass("hover");},
            function () {$(this).removeClass("hover");}
        ); // hover

        $(".melodeon .item h3").each(function(){
                $(this).click(function(){
                    var this_this = this;
                    if ($(this.parentNode).hasClass("active")) return false;
                    $(".melodeon .item.active .pop-prod").slideUp("slow", function(){
                        $(".melodeon .item.active").removeClass("active");
                        $(".pop-prod",this_this.parentNode).slideDown();
                        $(this_this.parentNode).addClass("active");
                        }); // calback
                    }); // click;
            }); // each;

        // show/hide products popup
        if ($("div.pop-up").length){
            if ($.browser.msie){
                    $(".cat-details").height($(".pop-up").height());
                }
            $("div.pop-up").hover( // This need other solution
                // breadcrumbs hide is for suka IE
                function(){},
                function(){$(".breadcrumbs li h2").show();}
                ) // hover
            $("ul.categorys li a").each(function(e){
                this.onmouseover = function(){
                    quantity = $(this).attr('products_quantity');
                    text = quantity + ' product';
                    if (quantity != 1) text = text + 's';
                    $('#products_quantity').text(text);
                    $(".cat-details ul.active").removeClass("active");
                    $($(".cat-details ul")[e]).addClass("active");
                    return false;
                    } // mouseover
                }); // each
            } // if div.pop-up

        $("div.pop-up").mouseleave(function(){
          var total_quantity = $('ul#cat').attr('total_quantity');
          var text = total_quantity + ' product';
          if (total_quantity != 1) text = text + 's';
          $('span#products_quantity').text(text);
        });

        $("form.forgot a.close").click(function(){
            $("#login_popup_holder").removeClass("open");
            return false;
            }) //click
    }
}

Sputnik.Navigation = {
  redirectToItem : function(){
    url = $(this).parent().attr('rel');
    if (url) {
      location.href = url;
    }
  }
}

Sputnik.Dashboard = {
    init: function () {
        // messages and similar popup
        $(".dashboard .messages .controls a.reply").click(function(){
            Sputnik.Utils.center($("#reply-message").fadeIn());
            return false;
            });
        $(".dashboard .controls a.new-message").click(function(){
            $('div#new_message_container').fadeIn();
            return false;
            });
        $(".dashboard .controls a.new-user").click(function(){
            Sputnik.Utils.center($("#new-user").fadeIn());
            return false;
            });
        $(".header a.feedback").click(function(){
            Sputnik.Utils.center($("#new-feedback").fadeIn());
            return false;
            });
        $(".dashboard a.dns").click(function(){
            $("#dns-popup").fadeIn();
            return false;
            }); // click
        $('a#cancel_new_message').click(function(){
            $('#new_message_container').fadeOut(200);
            return false;
        });

        Sputnik.Utils.showErrorMessage();

        // Mail-list pictures: hover -> color, normal -> b/w
        $("ul.mail-list a").attr("target","blank");
        $("ul.mail-list a img").hover(
            function(){
                var this_img = $(this);
                this_img.attr("src", "hover-"+this_img.attr("src"));
                },
            function(){
                var this_img = $(this);
                this_img.attr("src", this_img.attr("src").slice(6));
                })

        $(".dashboard .controls a.new-product").click(function(){
            if (last_incomplete_product) {
              id = last_incomplete_product.product.id;
              step = last_incomplete_product.product.creation_step
              if (confirm('You have an incomplete product #'+ id  + '\nWhould you like to continue with that product?'))
              {
                location.href = printer_admin_products_path('/'+id+'/step'+step);
                return false;
              }
            }
            pos = $(this).parents().filter(".item-head"); // where to pos
            $("#new-product").css({
                top:pos.position().top+pos.height()+5,
                right:$(document).width()-pos.position().left-pos.width()
                }).fadeIn();
            return false;
            })

        // Show|hide Categories on Products-List screen
        $("#showhidecat").toggle(
            function(){
                $(".item-content", $(this).parents(".item")).slideDown();
                $(this).html("Hide");
                return false;
                },
                function(){
                $(".item-content", $(this).parents(".item")).slideUp();
                $(this).html("Show");
                return false;
                }); // toggle

        $(".message-popup").each(function(){
            var this_popup = $(this);
            $("a.close, a.cancel, a.action.cancel", this).click(function(){
                this_popup.fadeOut();
                Sputnik.FormHelpers.resetForm('form#new_user_message');
                return false;
                }) // click
            }) // each

            // hide error mesages onclick
        if($.browser.msie){
            $("table.orders tbody tr").hover(function(){$(this).addClass("hover")},function(){$(this).removeClass("hover")});
            } // if
        $(".errmsg").click(function(){$(this).fadeOut();});
    },

    getSearchResults: function() {
      params = {
        'product_name': $("input#product_name").val(),
        'authenticity_token': AUTH_TOKEN
      }
      $.get(products_path('/menu_search'), params,
        function(data){
          $('ul#search_categories_container').html(data);
        });
      return false;
    }
}

Sputnik.FormHelpers = {
    multipleCheckboxSelect: function(parent_checkbox, child_checkboxes) {
        if ($(parent_checkbox).attr('checked')) {
            $(child_checkboxes).attr('checked', 'checked');
        } else {
            $(child_checkboxes).attr('checked', '');
        }
    },

    selectedCheckBoxesIds: function(checkboxes_name) {
        checkboxes = $('input:checkbox[name="' + checkboxes_name + '"]:checked');
        selected_items_ids = new Array();
        checkboxes.each(function() {
            selected_items_ids.push(this.value);
            });
        return selected_items_ids;
    },

    resetForm: function(form_selector) {
      $(form_selector + ' input').val('');
      $(form_selector + ' select').val('');
      $(form_selector + ' textarea').val('');
      $(form_selector + ' checkbox').val('');
      $(form_selector + ' radio').val('');
      return false;
    }
}

$(document).ready(function() {

    // Fix select fro Safari on Mac
    if (!!($.browser.safari & window.navigator.platform.search("Mac") != -1)){
        $("select.big").css({'margin-top': 6});
        }
    Sputnik.PopUp.init();
    Sputnik.Dashboard.init();
    Sputnik.Utils.halfHeight();

    $('tr td:not(:has(:checkbox))').click(Sputnik.Navigation.redirectToItem);

    // To prevent form submit
    $("input#product_name").keypress(function(e){
      var key;
      if(window.event) {
         key = window.event.keyCode; //IE
      } else {
         key = e.which; //firefox
      }
      return (key != 13);
    });

    $("input#product_name").keyup(function(){
        Sputnik.Dashboard.getSearchResults();
        return false;
    });

    // Stop propogation for message star
    $('.messages p.meta span.star').click(function(event){event.stopPropagation()});

    Sputnik.Utils.prepareErrorMessage();

    $("body.static-page .page-content").css("min-height", $("body.static-page").height() - $("body.static-page .header").height() - $("body.static-page .footer").height());

    $(".palettes .palettes-wrapper").each(function(){
       $(".palette:last", this).addClass("last");
    })
    $("ul.themes li").each(function(){
      var palette = $(".palettes .palettes-wrapper", this).children(".palette");
      $(".palettes .palettes-wrapper", this).width( $(palette).outerWidth(true) * $(palette).length - parseInt($(palette).css("margin-right")));
    });

    //columns adjusting on admin/orders
    var height1 = $(".dashboard .item.triple-double .item-content").outerHeight();
    var height2 = $(".dashboard .item.triple .item-content").outerHeight();
    var height = height1 > height2 ? height1 : height2;
    $(".dashboard .item.triple .item-content").height(height);
    $(".dashboard .item.triple-double .item-content").height(height);

    Sputnik.Utils.equalBlocksAdjusting();

    //columns adjusting on admin/transactions
    height1 = $(".dashboard .item .item-content .left").outerHeight();
    height2 = $(".dashboard .item .item-content .right").outerHeight();
    height = height1 > height2 ? height1 : height2;
    $(".dashboard .item .item-content .left").height(height);
    $(".dashboard .item .item-content .right").height(height);

    // Show warning if client uses IE6 of FF2
    if (($.browser.msie && $.browser.version.substr(0,1) < 7) || ($.browser.mozilla && $.browser.version.substr(0,3) < 1.9)) {
      $('div#outdated_browser_message').show();
    }

});