


var Bellaga = function() {
  return {
    uid: Math.random(),
    domain: document.domain,
   
    error: function ( message ) {
      return this.showMessage('error', message);
    },

    post: function ( path, params, cb ) {
      params['pbr'] = $.cookie('pbr');
      $.post(path, params, cb, 'json');
    },

    message: function ( message ) {
      return this.showMessage('message', message);
    },

    showMessage: function (type, message) {
      $('#dyn-message').hide();
      $('#dyn-message').html(message);
      $('#dyn-message').removeClass('error').removeClass('message').addClass(type);
      $('#dyn-message').fadeIn()
      .animate({opacity: 1.0}, 4000)
      .fadeOut('slow');
    },

    cookieSet: function (name, value) {
      return $.cookie(name, value,  { path: '/', domain: '.' + this.domain, expires: 700 });
    },

    cookieGet: function (name) {
      return $.cookie(name);
    },

    shortUrl: function ( url, callback ) {
      account = "blga.in";

      if (typeof url == 'undefined' || url == null )
      url = window.location;

      //What is this wooly thing?  It looks awesome!
      var wooly = "http://api.woolyapp.com/url/shear?format=json&domain=" + account + "&url=" + escape(url) + "&jsoncallback=?";
      
      $.getJSON(wooly, callback);
    },

    awning: function ( text ) {
      $("#awning").hide();
      $("#awning .awning-content").html(text);
      $("#awning").fadeIn("slow");

      $("#awning:close").click(function () {
        $('#awning').fadeOut("slow");
      });

      setTimeout(function() {$('#awning').fadeOut("slow");}, 10000);
    },

    poll: function () {
      if ( ! Bellaga.poll_id)
      return;

      if (Bellaga.poll.xhr == undefined) {
        $(window).unload( function () {
          Bellaga.poll.xhr.abort();
        });
      }

      Bellaga.poll.xhr = $.ajax({
        async: true, /* If set to non-async, browser shows page as "Loading.."*/
        dateType: 'json',
        ifModified: true,
        timeout: 15*60*1000, /* Timeout in ms */
        type: "GET",
        url: "/poll?id=" + Bellaga.poll_id,

        beforeSend: function (xhr) {
          // forcing the last modified and etag headers
          if (Bellaga.poll.last_modified) {
            xhr.setRequestHeader('If-Modified-Since', Bellaga.poll.last_modified);
            xhr.setRequestHeader('If-None-Match', Bellaga.poll.etag);
          }
        },

        success: function (payload, status, xhr) {
          // jq 1.4+ thinks aborted == success. good job.
          if (payload == undefined) {
            return;
          }

          Bellaga.poll.last_modified = xhr.getResponseHeader('Last-Modified');
          Bellaga.poll.etag = xhr.getResponseHeader('Etag');

          var notification = $('<div class="popup-box" title="click to remove">' + payload.data + '</div>').click(function () {
            $(this).fadeOut(function () {
              $(this).remove();
            });
          });
          setTimeout(function () { notification.click() }, 3000);
          $('#popup-cont').prepend(notification);

          Bellaga.poll();
        },

        error: function(XMLHttpRequest, textStatus, errorThrown) {
          if (textStatus == 'timeout' ) {
            return setTimeout(Bellaga.poll, 100);
          }

          if (textStatus == 'notmodified' ) {
            return setTimeout(Bellaga.poll, 1000);
          }

          //A real error, lets just wait 15 seconds
          return setTimeout(Bellaga.poll, 15000);
        }
      });
    },

    geocode: function ( address, cb ) {
      Bellaga.post('/api/geocode',{address: address}, cb);
    }
  }
} ();



//API


Bellaga.api = function() { return {
    base: '/api',
    ajax: function (url, method, data, cb, cb_err) {
    
      //CSRF - You now know the secret of PBR!
      data['pbr'] = $.cookie('pbr');
      
      return $.ajax({
        url: url, 
        data: data, 
        cache: false,
        type: method,
        success: cb,
        error: cb_err,
        dataType: 'json'
      });

    },
    _post: function ( url, data, cb ) {
      return this.ajax(url,'POST', data, cb );
    },
    _get: function ( url, data, cb ) {
      return this.ajax(url,'GET', data, cb );
    },    
    _put: function ( url, data, cb ) {
      return this.ajax(url,'PUT', data, cb );
    },
    _delete: function ( url, data, cb ) {
      return this.ajax(url,'DELETE', data, cb );
    }
    
}} ();

    
Bellaga.user = { base: Bellaga.api.base + '/user' };

/****
*
* USER CART 
*
****/

Bellaga.user.cart = function() { return {
  base: Bellaga.user.base + '/cart',
  add: function (iqid, cb) {
    Bellaga.api._put(
      this.base + '/' + iqid,
      {detail: 'high'},
      cb);  
  },
  remove: function (iqid,detail, cb) {
    Bellaga.api._delete(
      this.base + '/' + item,
      {detail: detail},
      cb);
  }
  
}}();


/****
*
* USER FAVORITE 
*
****/

Bellaga.user.favorite = function() { return {
  base: Bellaga.user.base + '/favorite' ,
  love: function (item_id, cb) {
    
    Bellaga.api._put(
      this.base + '/love/' + item_id,
      {detail: 'medium', action: 'love'},
      cb
    );
  
  },
  hide: function ( item_id, cb) {
  },
  remove: function (item_id, cb) {
  
    Bellaga.api._delete(
      this.base + '/' + item_id,
      {detail: 'low'},
      cb
    );
    
  }
 
}}();


/****
*
* STYLEBOOK FAVORITE 
*
****/

Bellaga.stylebook = { 
  base: Bellaga.api.base + '/stylebook',
  entry: function (entry_id,cb,cb_err) {
     Bellaga.api._get(
      this.base + '/look/' + entry_id,
      {detail: 'high'},
      cb,
      cb_err
    );
    
    
    
  },
  search: function (params, cb, cb_err) {
    
    params.detail = 'high';
    
    Bellaga.api._get(
      this.base + '/looks',
      params,
      cb,
      cb_err
    );
    
  }
  
};
 
Bellaga.stylebook.favorite = function() { return {
  base: Bellaga.stylebook.base + '/favorite' ,
  
  love: function (entry_id, cb) {
    
    Bellaga.api._put(
      this.base + '/' + entry_id,
      {detail: 'high'},
      cb
    );
  },
  remove: function (entry_id, cb) {
  
    Bellaga.api._delete(
      this.base + '/' + entry_id,
      {detail: 'low'},
      cb
    );
    
  }
 
}}();

  

//Nothing like growl at all
Bellaga.rwl = function (title,text, image, sticky) {

  $.gritter.add({
    title: title,
    text: text,
    image: image,
    sticky: sticky
  });

}


Bellaga.publish = { fb: {} };

Bellaga.publish.fb.entry = function (entry_id, cb) {
  
  Bellaga.stylebook.entry(entry_id,
  function(data) {
    var entry = data.data;
    var entry_title = (new Date(entry.post_ts * 1000)).format('mmmm dS, yyyy', true) + ': ' + entry.profile.user.display_name + '\'s StyleBook look';
    
    FB.ui(
     {
       method: 'stream.publish',
       message: entry_title,
       attachment: {
         'media': [
              { 
                'type': 'image', 
                'src':  entry.primary_image['460x'], 
                'href': entry.url}],
         name: entry_title,
         caption: entry.title,
         description: entry.description,
         href: entry.url
       },
       action_links: [
         { text: 'Vote/Comment', href: entry.url }
       ] /*,
       user_message_prompt: 'user prompt text'*/
     },
     cb
   );

  }); 
}


Bellaga.event = function() {
  return {
    addToCart: function (variation) {
  
      var item  = variation.item;
      var img   = item.primary_image['50x50'];
      var title = "Added to cart<div class='rwl-icon cart'></div>";
      var shop  = item.shop;
      
      var shop_url = '<a href="' + shop.url + '">' + $('<div>').html(shop.title).text() + '</a>';
      var item_url = '<a href="' + item.url + '">' + $('<div>').html(item.title).text() + '</a>';
      
      if (variation.name) {
        item_url += ' - ' + variation.name;
      }
      
      Bellaga.rwl(title, item_url + '<p>by ' + shop_url, img, false);
          
    },
    updateCartCount: function (count) {
      $('#cart-count').text(count + ' item' + (count == 1?'':'s'));
    },
    
    favorite: function (item) {
      
      var img   = item.primary_image['50x50'];

      var title = "Added to favorites<div class='rwl-icon heart'></div>";
      var shop  = item.shop;
      
      var shop_url = '<a href="' + shop.url + '">' + $('<div>').html(shop.title).text() + '</a>';
      var item_url = '<a href="' + item.url + '">' + $('<div>').html(item.title).text() + '</a>';
      
      Bellaga.rwl(title, item_url + '<p>by ' + shop_url, img, false);
      
    },
    
    favorite: function (item) {
      
      var img   = item.primary_image['50x50'];

      var title = "Added to favorites<div class='rwl-icon heart'></div>";
      var shop  = item.shop;
      
      var shop_url = '<a href="' + shop.url + '">' + $('<div>').html(shop.title).text() + '</a>';
      var item_url = '<a href="' + item.url + '">' + $('<div>').html(item.title).text() + '</a>';
      
      Bellaga.rwl(title, item_url + '<p>by ' + shop_url, img, false);
      
    },
  }
}();

Bellaga.event.stylebook = function() {
  return {
   
    favorite: function (entry) {
      
      var img   = entry.primary_image['50x50'];

      var title = "Added to favorites<div class='rwl-icon heart'></div>";
      var profile  = entry.profile;
      
      var profile_url = '<a href="' + profile.url + '">' + escapeHtml(entry.profile.user.display_name) + '</a>';
      var entry_url   = '<a href="' + entry.url + '">' + escapeHtml(entry.title) + '</a>';
      
      Bellaga.rwl(title, entry_url + '<p>by ' + profile_url, img, false);
      
    },
  }
}(); 
  
/* Initialize drop down menu */
$(function() {

  $('ul.top-tab li').each(function() {

    $('> ul', this).parent().addClass('has-child');

    $(this).mouseleave(function(e){
      $('> ul', this).each(function() {
        $(this).hide();
      });

    });

    $(this).mouseenter(function(){
      $('> ul', this).each(function() {
        $(this).show();
      });
    });

  })

  //Warn on change forms
     
  $('form.warn-on-change input').change(function() {
      
    $(window).bind('beforeunload', function () {
     //confirm("You have unsaved changes, sure you want to continue?");
     return "Any changes you made will be lost.";   
    })
    
  });
  
  $('form.warn-on-change').click(function() {
    $(window).unbind('beforeunload');
  })
  
  $('#search-submit').click(function(click) {
    click.preventDefault();
    $('#search-form form').submit();
  });

  if ($('#search-box').val() == '') {
    $('#search-box').val('search');
    $('#search-box').addClass('unselected');
  }

  $('#search-box').focus(function() {

    $(this).removeClass('unselected');

    if ($(this).val() != 'search') {
      return;
    }

    $(this).val('');

  });

  //Search box bluring
  $('#search-box').blur(function() {

    if ($(this).val() == '') {
      $(this).addClass('unselected');
      $(this).val('search');
    }

  });

});


//Allows you to create multiple timeouts that clear each other.

var timeouts = {};
  
function timeout ( id, cb, delay) {
  
  if (typeof timeouts[id] != 'undefined') {
    clearTimeout(timeouts[id]);
  }
  
  if (cb == null) {
    timeouts[id] = null;
  } else {
    timeouts[id] = setTimeout(cb, delay);
  }
  
}
  




//Allows you to create multiple timeouts that clear each other.

var timeouts = {};
  
function timeout ( id, cb, delay) {
  
  if (typeof timeouts[id] != 'undefined') {
    clearTimeout(timeouts[id]);
  }
  
  if (cb == null) {
    timeouts[id] = null;
  } else {
    timeouts[id] = setTimeout(cb, delay);
  }
  
}
  

function escapeHtml ( html, cr2br ) {

  if (html == null) {
    return html;  
  }
  
  var replacements = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"]];
  
  for(i in replacements) {
    html = html.replace(replacements[i][0], replacements[i][1]);
  }
  
  if (cr2br) {
    html = html.replace(/\n/g, "<br>\r");
  }
  
  return html;
    
}

  
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
  var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
  timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
  timezoneClip = /[^-+\dA-Z]/g,
  pad = function (val, len) {
    val = String(val);
    len = len || 2;
    while (val.length < len) val = "0" + val;
    return val;
  };

  // Regexes and supporting functions are cached through closure
  return function (date, mask, utc) {
    var dF = dateFormat;

    // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
    if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
      mask = date;
      date = undefined;
    }

    // Passing date through Date applies Date.parse, if necessary
    date = date ? new Date(date) : new Date;
    if (isNaN(date)) throw SyntaxError("invalid date");

    mask = String(dF.masks[mask] || mask || dF.masks["default"]);

    // Allow setting the utc argument via the mask
    if (mask.slice(0, 4) == "UTC:") {
      mask = mask.slice(4);
      utc = true;
    }

    var	_ = utc ? "getUTC" : "get",
    d = date[_ + "Date"](),
    D = date[_ + "Day"](),
    m = date[_ + "Month"](),
    y = date[_ + "FullYear"](),
    H = date[_ + "Hours"](),
    M = date[_ + "Minutes"](),
    s = date[_ + "Seconds"](),
    L = date[_ + "Milliseconds"](),
    o = utc ? 0 : date.getTimezoneOffset(),
    flags = {
      d:    d,
      dd:   pad(d),
      ddd:  dF.i18n.dayNames[D],
      dddd: dF.i18n.dayNames[D + 7],
      m:    m + 1,
      mm:   pad(m + 1),
      mmm:  dF.i18n.monthNames[m],
      mmmm: dF.i18n.monthNames[m + 12],
      yy:   String(y).slice(2),
      yyyy: y,
      h:    H % 12 || 12,
      hh:   pad(H % 12 || 12),
      H:    H,
      HH:   pad(H),
      M:    M,
      MM:   pad(M),
      s:    s,
      ss:   pad(s),
      l:    pad(L, 3),
      L:    pad(L > 99 ? Math.round(L / 10) : L),
      t:    H < 12 ? "a"  : "p",
      tt:   H < 12 ? "am" : "pm",
      T:    H < 12 ? "A"  : "P",
      TT:   H < 12 ? "AM" : "PM",
      Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
      o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
      S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
    };

    return mask.replace(token, function ($0) {
      return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
    });
  };
}();

// Some common format strings
dateFormat.masks = {
"default":      "ddd mmm dd yyyy HH:MM:ss",
shortDate:      "m/d/yy",
mediumDate:     "mmm d, yyyy",
longDate:       "mmmm d, yyyy",
fullDate:       "dddd, mmmm d, yyyy",
shortTime:      "h:MM TT",
mediumTime:     "h:MM:ss TT",
longTime:       "h:MM:ss TT Z",
isoDate:        "yyyy-mm-dd",
isoTime:        "HH:MM:ss",
isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
  dayNames: [
  "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
  "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
  ],
  monthNames: [
  "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
  ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
  return dateFormat(this, mask, utc);
};

function showTooltip(x, y, contents) {
  $('<div id="tooltip">' + contents + '</div>').css( {
    position: 'absolute',
    display: 'none',
    top: y + 5,
    left: x + 5,
    border: '1px solid #fdd',
    padding: '2px',
    'background-color': '#fee',
    opacity: 0.80,
    'z-index': "10000"
  }).appendTo("body").fadeIn(200);
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
