var ScrollCtl = function(initialPosition, length) {
  var position = initialPosition;
  var queueCfg = {position: 'end', scope: 'scrollctl'};

  function onoff_arr(arr, onoff) {
    var lnk = $('products_scroller_holder').up().down(arr);
    lnk[onoff ? 'addClassName' : 'removeClassName']('disabled');
    lnk.blur();
  }

  return {
    disableArrows: function() {
      onoff_arr('.to_left', position <= 0);
      onoff_arr('.to_right', position >= (length-1));
    },
    moveLeft: function() {
      var e;
      if (position > 0) {
        position = position - 1;
        new Effect.Move($('products_scroller_holder'), { x: 100, queue: queueCfg});
      }
      this.disableArrows();
    },
    moveRight: function() {
      if (position < (length-1)) {
        position = position + 1;
        new Effect.Move($('products_scroller_holder'), { x: -100, queue: queueCfg});
      }
      this.disableArrows();
    }
  }
}
function registerPopupHandlers() {
  $$('.scroller_popup').each(function(popup) {
    var scrollerItem = popup.up('.scroller_item');
    Event.observe(scrollerItem, 'mouseover', function() {popup.show();});
    Event.observe(scrollerItem, 'mouseout', function() {popup.hide();});
  });
}
function maximizeScroller() {
  $$('.scroller').each(function(scroller) {
    scroller.setStyle({width: (4 * 100) + 'px'});
  });
  $$('.scroller').each(function(scroller) {
    var contentWidth = scroller.up('.content').getWidth();
    var maxItems = Math.floor(contentWidth / 100);
    scroller.setStyle({width: (maxItems * 100) + 'px'});
  });
}
function makeProductsDraggable() {
  var cart = $('cart');
  if (cart) {
    $$('.product_image').each(function(img) {
      var dr = new Draggable(img, {
        revert: true,
        endeffect: function(element) {
          new Effect.Opacity(element, {duration:0.2, from:0.7, to:1.0}); 
        },
        onStart: function() {
          cart.highlight();
        },
        starteffect: function(element) {
          new Effect.Opacity(element, {duration:0.2, from:1.0, to:0.7}); 
        },
        onDropped: function(el) {
          if (Prototype.Browser.IE && (!el.currentStyle.hasLayout)) {
            el.setStyle({zoom: 1});
          }
          el.setStyle({opacity: 0});
          setTimeout(function() {          
            new Effect.Opacity(img, {from: 0, to: 1.0, duration: 0.5});
          }, 1000);
        }
      });
      var click_handler = function(draggable, event) {
        if (!draggable.dragging) {
          var prod_id = img.className.gsub(/^.*_id_(\d+).*$/, '#{1}');
          var product_link = $('product_'+ prod_id +'_link');
          if (product_link) {
            location.href = product_link.href;
          }
        }
      }
      Event.observe(img, 'mouseup', click_handler.curry(dr));
    });
    Droppables.add(cart, {
      accept: 'product_image',
      onDrop: function(img) {
        var prod_id = img.className.gsub(/^.*_id_(\d+).*$/, '#{1}');
        new Ajax.Updater('cart', '/buy/'+prod_id, {asynchronous:true, evalScripts:true, parameters:{}}); return false;
      }
    });
  }
}
function registerBuyAnimation() {
  $$('.buy').each(function(lnk) {
    Event.observe(lnk, 'click', function() {
      var current_product = $$('.content .product_image').find(Element.visible);
      if (current_product) {      
        var ghost = $(current_product.cloneNode(true));
        ghost.removeAttribute('id');
        var origin = current_product.cumulativeOffset();
        ghost.setStyle({position: 'absolute', left: origin.left + 'px', top: origin.top + 'px'});
        $(document.body).insert(ghost);
        var destination = $('cart').cumulativeOffset();
        new Effect.Parallel([
            new Effect.Move(ghost, {sync: true, mode: 'absolute', x: destination.left, y: destination.top}),
            new Effect.Scale(ghost, 20, {sync: true})
          ], {
          afterFinish: function() {
            ghost.remove();
          }
        });
      }
    });
  });
}

document.observe('dom:loaded', function() {
  registerPopupHandlers();
  registerBuyAnimation();
  makeProductsDraggable();
  maximizeScroller();
  collapseOnLoad();
});
Event.observe(window, 'resize', function() {
  maximizeScroller();
});

function collapseOnLoad() {
  $$('.content .collapsible_block_header').each(function(hdr) {
    if (!hdr.hasClassName('show_me')) {
      hdr.next('.collapsible_block').hide();
    }
    hdr.observe('click', function() {
      Effect.toggle(hdr.next('.collapsible_block'), 'blind', {duration: 0.3});
    })
  })
}

/* top banner */
document.observe('dom:loaded', function() {
  if (!$('breadcumbs')) {
    return;
  }
  var width = $$('body').first().getWidth() - $('breadcumbs').getWidth() - 300;
  var links = ['http://www.lookatme.ru/flows/mesta-nado-znat/posts/61433-freshmania-salon-krasotyi-kotorogo-myi-dolgo-zhdali', 'http://freshmania.ru/info/boutique', 'http://www.lookatme.ru/flows/moda/posts/64666-novaya-kollektsiya-hair-lukov-remix-ot-tigi'];
  var tb = new Element('div', {id: 'tb1'});
  $('header').insert({'top': tb})
  var xs = $A([110, 274, 388, 532, 648, 742, 854]);
  $R(0, xs.length - 2).each(function(i) {
    var x_left = xs[i];
    var x_right = xs[i+1];
    var face = new Element('a', {id: 'face'+i, 'class': 'tb2', href: links[i % links.length]});
    tb.insert(face);
    if (x_right > width) {
      face.hide();
    }
    face.setStyle({
        left: x_left + "px",
        width: (x_right-x_left)+'px',
        backgroundPosition: "-"+ x_left +"px 0"
    });
    face.observe('mouseover', function(ev) {
      this.setStyle({backgroundImage: "url('/images/tb2.jpg')"});
    }.bind(face));
    face.observe('mouseout', function(ev) {
      this.setStyle({backgroundImage: "url('/images/tb1.jpg')"});
    }.bind(face));
  });
  Event.observe(window, 'resize', function() {
    var width = $$('body').first().getWidth() - $('breadcumbs').getWidth() - 300;
    $R(0, xs.length - 2).each(function(i) {
      var x_right = xs[i+1];
      if (x_right < width) {
        $('face'+ i).show();
      } else {
        $('face'+ i).hide();
      }
    })
  })
})

/* twitter stuff */
function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

