/* -*- js2 -*-
 */

DetailPageSwitcher = function() {

    // product reviews
    this.pageContainer = jQuery('#details_pages');
    if (this.pageContainer.length < 1)
        return;
    this.pages = this.pageContainer.find('.details');
    this.pageSwitchers = jQuery('#details_pages_switcher .trigger_page');
    this.placeSwitchers = jQuery('#details_pages_switcher .trigger_place');

    var that = this;

    this.switchPlace = function(id, anim) {
        // since we're switching positions in the viewport
        // and not the page, disable all highlights on the buttons

        // my god, we gotta rename these classes or we die
        this.pageSwitchers
            .removeClass('titlebar_btn')
            .addClass('bar_btn');

        jQuery.scrollTo('#'+id, { duration: 450, easing: 'easeInOutCirc' });
        return false; // prevent browser navigation
    };

    this.switchPage = function(id, anim) {
        var showing = jQuery('#'+id);
        var destHeight = showing.height() + 20;
        var currHeight = this.pageContainer.height();
        var midHeight = (destHeight + currHeight)/2;

        if (anim == null) {
            anim = true;
        }

        // my god, we gotta rename these classes or we die
        this.pageSwitchers
            .removeClass('titlebar_btn')
            .addClass('bar_btn');
        this.pageSwitchers.filter('.show_'+id)
            .removeClass('bar_btn')
            .addClass('titlebar_btn');

        this.pageContainer.css({ overflow: 'hidden',
                                 height: currHeight });
        this.pageContainer.
            clearQueue().
            animate({ opacity: 0.0,
                      height: midHeight },
                    anim ? 500 : 0,
                    'easeInCirc',
                    function() {
                        // switch the content and animate some more
                        that.pages.css({display: 'none'});
                        showing.css({display: 'block'});
                        that.pageContainer.
                            clearQueue().
                            animate({ opacity: 1.0,
                                      height: destHeight
                                    }, 
                                    anim ? 500 : 0,
                                    'easeOutCirc');
                    });
    };

    this.pageSwitchers.
        click(function(ev) {
                  var m = /show_(\w+)/.exec(ev.target.className);
                  var destId = m[1];
                  that.switchPage(destId);
              });
    this.placeSwitchers.
        click(function(ev) {
                  var m = /show_(\w+)/.exec(ev.target.className);
                  var destId = m[1];
                  that.switchPlace(destId);
              });

    this.switchPage(this.pages.eq(0).attr('id'), false);
};

jQuery.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
};

var AwesomeSelect = function () {
    this.id = null;
    this.selfSelector = null;
    this.replacementSelect = null;
    this.status = true;
    this.selectEntries = new Array();
    this.value = null;

    this.init = function(sel) {
        if (jQuery.browser.msie /* && jQuery.browser.version == 6 */)
            return;
        this.replacementSelect = jQuery(sel);
        this.id = Math.floor(Math.random()*65536);
        this.selfSelector = '#awesome_select_'+this.id;
        this.value = this.getValue();
        jQuery(this.replacementSelect).before(this.buildMenu());
        var p = jQuery(this.selfSelector).find('[rel$=true]').html();
        this.setValue(this.value, jQuery(this.selfSelector).find('[rel$=true]').html(), false);
        this.toggleSubmenu();
        var position = this.replacementSelect.offset();
        this.bindEvents();
        this.replacementSelect.css('visibility', 'hidden');
    };

    this.getValue = function() {
        var options = this.replacementSelect.find('option');
        for (var i = 0; i < options.size(); i++) {
            this.selectEntries[i] = { label: options.eq(i).html(),
                                      value: options.eq(i).val(),
                                      selected: options.eq(i).attr('selected')};
        }
        return this.replacementSelect.val();
    };

    this.setValue = function(val, label, trig) {
        jQuery(this.selfSelector+'_selected').html(label);
        if (val != this.value && trig) {
            this.replacementSelect.val(val);
            this.replacementSelect.trigger('change');
        }
    };

    this.toggleSubmenu = function() {
        jQuery(this.selfSelector+' div.awesome_submenu').slideToggle('fast');
        this.status = !this.status;
        jQuery(this.selfSelector+' .awesome_toggler').attr('src', ((this.status) ? '/_gfx/ArrowUp.png' : '/_gfx/ArrowDown.png'));
    };

    this.buildMenu = function() {
        var returnHTML = '<div id="'+this.selfSelector.substring(1)+'" class="'+this.replacementSelect.attr('class')+'">\n';
        returnHTML += '<div style="position: relative"><img src="/_gfx/ArrowUp.png" class="awesome_toggler" /><span id="'+this.selfSelector.substring(1)+'_selected"></span></div>\n';

        returnHTML += '<div class="awesome_submenu">\n';

        for (var i = 0; i < this.selectEntries.length; i++) {
            returnHTML += '<div class="awesome_entry" rel="'+this.selectEntries[i].value+' '+this.selectEntries[i].selected+'">'+this.selectEntries[i].label+'</div>\n';
        }
        returnHTML += '</div>';
        return returnHTML;
    };

    this.bindEvents = function () {
        var callback = this;
        jQuery(this.selfSelector+' div').eq(0).click( function(e) {
            callback.toggleSubmenu();
            e.stopPropagation();
        });
        jQuery(this.selfSelector+' div.awesome_entry').click( function (e) {
            callback.toggleSubmenu();
            callback.setValue(jQuery(this).attr('rel').split(' ')[0], jQuery(this).html(), true);
            e.stopPropagation();
        });
        jQuery(document).click( function () {
            if (callback.status) {
                callback.toggleSubmenu();
            }
        });
    };
};


var TopTenScroller = {
    view: null,

    init: function() {
        this.view = $(".control_topten .products");
    },

    doTimerThing: function() {
         this.view.scrollTo(this.view.find("form").eq(1), 2000, {
            easing: 'easeOutBack',
            onAfter: function() {
                var html = TopTenScroller.view.find("form").eq(0).outerHTML();
                TopTenScroller.view.find("form").eq(0).remove();
                TopTenScroller.view.scrollTo(TopTenScroller.view.find("form").eq(0), 0);
                TopTenScroller.view.append(html);

                var newOne = TopTenScroller.view.find("form:last");

                TopTenScroller.view.find("a[rel=gallery]").unbind('click').fancybox({
                    'overlayShow' : true,
                    'zoomSpeedIn' : 600,
                    'zoomSpeedOut' : 500,
                    'easingIn' : 'easeOutBack',
                    'easingOut' : 'easeInBack'
                });
            } } );
    }
};


$(document).ready(
    function() {

        jQuery('select.awesome').each(
            function() {
                var aSelect = new AwesomeSelect;
                aSelect.init(this);
            });

        //SectionJS.makeMagicBaskets();
        jQuery('.item input.submit').click(
            function() {
                /// \todo : make a good and universal Section.js
                var item = jQuery(this).closest(".item");
                var pid = parseInt(item.find('input[name=pid]').val());
                var data = {'class': 'Basket',
                            'method': 'addToBasket',
                            'pid' : pid,
                            'count' : 1};

                $.getJSON('/_json/',
                          data,
                          function(json) {
                              if (SectionJS) {
                                  var totalBasket = $('.basket_info img');
                                  SectionJS.setBasketCount(totalBasket, json.counts.total);
                                  var totalPrice = jQuery('.basket_info .basket_sum');
                                  if (totalPrice.size() > 0) {
                                      totalPrice.html(json.total_value);
                                  };
                              };
                              // would have to wait at least 400ms before reading the new basket count...
                              if (BasketThing) {
                                  BasketThing.basketCount = json.counts.total;
                                  BasketThing.setDefaultContent();
                                  BasketThing.showTheThing();
                                  setTimeout("BasketThing.hideTheThing()", 3000);
                              };
                              for(var pid in json.counts) {
                                  var box = $('#product_box'+pid);
                                  if (box.size() > 0) {
                                      var target = box.find('.item_count');
                                      target.each(
                                          function() {
                                              var jQ = $(this);
                                              if (jQ.text().replace(/\s/g, '') == '') {
                                                  var textBefore = (jQ.closest('.product_tile').size() == 0) ? 'W koszyku: ' : '';
                                                  jQ.prepend(textBefore+"<div class='basket_count'>0</div>");
                                              }
                                              SectionJS.setBasketCount(jQ, json.counts[pid]);
                                          });
                                  }
                              }
                          });
                $(this).blur();
                return false;
            });

        $('.basket_to_basket_submit').ifixpng('scale');

        $("a[rel=lightbox]").each(
            function () {
                $(this).fancybox(
                    {
                        'overlayShow' : true,
                        'zoomSpeedIn' : 600,
                        'zoomSpeedOut' : 500,
                        'easingIn' : 'easeOutBack',
                        'easingOut' : 'easeInBack'
                    });
            });

        $("a[rel=gallery]").fancybox(
            {
                'overlayShow' : true,
                'zoomSpeedIn' : 600,
                'zoomSpeedOut' : 500,
                'easingIn' : 'easeOutBack',
                'easingOut' : 'easeInBack'
            });

        if (SectionJS.oldIE) {
            // ie6 hacks
        };

        basketView = new BasketViewJS();
        //basketView.refreshPriceToPay();
        BasketThing.init();
        FacebookThing.init();
        new DetailPageSwitcher();
    });

function onlyNumbers(e)
{
    var keynum;
    var keychar;
    var numcheck;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /[\d\.\,\b]/;
    return numcheck.test(keychar) || (keynum == 188) || (keynum == 190);
}


function selectColor(domElem, prodId, valueStr) {
    var i = 1;
    var cSelector = document.getElementById('check_color_selector_' + prodId + '_1');
    for (i = 2; cSelector != null; i++) {
        cSelector.src = "_gfx/unchecked.gif";
        cSelector = document.getElementById('check_color_selector_' + prodId + '_' + i);
    }
    var color;
    var colorName;
    var re = /^([a-fA-F0-9]+)( (.*))?$/;
    color = valueStr.replace(re, "$1");
    colorName = valueStr.replace(re, "$3");
    var input = document.getElementById("options_color_" + prodId);
    input.value = colorName;
    cSelector = document.getElementById('check_' + domElem.id);
    cSelector.src = "_gfx/checked.gif";
}

