/* DON'T LOOK AT ME, I'M HIDEOUS */

/***********************************************
*
* Just look at me, I'm cuuuuuute
*
*
*    Zzzzz  |\      _,,,--,,_        +-----------------------------+
*           /,`.-'`'   ._  \-;;,_    | Why is there always a cat   |
*          |,4-  ) )_   .;.(  `'-'   | on whatever you're editing? |
*         '---''(_/._)-'(_\_)        +-----------------------------+
*
*
*************************************************/


/***********************************************
*
*  You will forget a console log!  
*
*************************************************/

if (typeof console == 'undefined') {
  console = { log: function(){} };
}

if (typeof R29 == 'undefined') {
  R29 = {};
}

/***********************************************
*
*  Img Preloading  
*
*************************************************/
 
R29.image = {
  cache: [],
  lazyloadInit: false,
  preLoad: function ( images ) {
  
   for (var i in images) {
      var cacheImage = document.createElement('img');
      cacheImage.src = images[i];
      R29.image.cache.push(cacheImage);
    }
    
  },
  lazyload: function( containerSelector ) {
    
    $(containerSelector).each(function(){
      
      if ($(this).complete)
        return;
      
      $(this)
        .hide()
        .attr('original_src', $(this).attr('src'))
        .attr('src','');
    });
    
    if (R29.image.lazyloadInit) {
      return;
    }
    
    R29.image.lazyloadInit = true;
    
    $(window).load(function(){
     $('img[original_src]').each(function(){
          if ($(this).attr('src') != "") {
            return;
          }
          
          $(this).attr('src',$(this).attr('original_src')).load(function(){
          $(this).fadeIn();
        }).each(function(){ //In case it's in cache, fire on load.
          if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) $(this).trigger("load");
        });
      });     
    });
    
  }
}

/***********************************************
*
*  Remote  
*
*************************************************/
 
R29.remote = {
  include_js: function ( src ) {
    var   e = document.createElement('script');
    e.async = true;
    e.src   = src;
    document.getElementById('js-cont').appendChild(e);
  }
}

/***********************************************
*
*  Tracking 
*
*************************************************/

R29.tracking = {
  
  //Refresh analytics tracking to better reflect pageviews
  refresh: function () {
  
    //Google
    pageTracker._trackPageview();
    
    //Comcore
    COMSCORE.beacon({ c1:2, c2:"7395029",c3:"www.refinery29.com", c4:currentUrl, c5:"", c6:"", c15: val});
    
    //Quantcast
    _qoptions={
      qacct:"p-fesXMHo90Ka_A"
    };
    
    _qpixelsent = new Array();
    
    quantserve();
    
    //ChartBeat
  
    if (typeof pSUPERFLY != 'undefined') {
      pSUPERFLY.virtualPage(document.location.href.replace(/http(s)?\:\/\/([a-z0-9\.]+)/,''));
    }

 }

};


/***********************************************
*
*  Stats 
*
*************************************************/

/*
R29.stats.add([['load_time',{}, 1]]);
*/

R29.stats = {
  data: [],
  queue: function (stats) {
    try {
      for (var i in stats) {
       R29.stats.data.push(stats[i]);
      }
    } catch (err) {};
  },
  send: function(data) {
  
    try {
      var img_src = R29.api.baseUrlLocal + '/stats?q=' + escape(JSON.stringify(data)) + '&' + (new Date()).getTime();
      var statImage = document.createElement('img');
      statImage.src = img_src;
    } catch (err) {};
    
    return true;       
  },
  commit: function() { 
    if (R29.api.isRemote) return;
    R29.stats.send(R29.stats.data);
    R29.stats.data = []; 
  }
};






/************************************************
*
*  ADS 
*  
*   Walker Told Me I Have ADS
*
************************************************/

R29.ads = {};

/************************************************
*
*  Refresh 
*  
*   Refreshes all the ads that match the element selector
*
************************************************/

R29.ads.refresh = function( elSelector ) {
  
  var ord = (new Date()).getTime();
  
  $(elSelector).each( function() {
    
    var src = $(this).attr('iframe-code');
    var sz  = $(this).attr('iframe-size');
    
    if (typeof src == 'undefined' || typeof sz == 'undefined') {
      return; //Guess we don't have 
    }
    
    var dims = sz.split(',');
    
    //var dim = dims[Math.floor((dims.length * Math.random()))]; //Get a random one
    //var dim = dims[dims.length - 1]; //Get the last one.
    var dim = dims[0]; //Get the first one.
    
    var w = dim.split('x', 2)[0];
    var h = dim.split('x', 2)[1];
    
    var iframe = $('<iframe/>')
    .attr('scrolling', 'no').attr('src', src.replace(sz, dim) + ';ord=' + ord)
    .attr('noresize', 'noresize')
    .attr('frameBorder', 0)
    .attr('border', 0)
    .attr('cellspacing', 0)
    .attr('marginwidth', 0)
    .attr('marginheight', 0);
    
    iframe.attr('height',h);
    iframe.attr('width',w);
    
    $(this).height(h);
    $(this).width(w);
    
    $(this).html('');
    
    //Delete ads served via embeds.
    $('embed').each(function() {$(this).attr('src').match(/(unicast|doubleclick)/)?$(this).parent().remove():''})

    $(this).append(iframe);

  });
  
};

//
// Welcome mat ads, you know you love em'
//

R29.ads.welcome = { 
  show: function( timeout_sec, tag){

    $('body').append( $('<div id="ad-center" style="position:fixed;z-index:1001;">' + tag + '</div>'));
    $('body').append( $('<div id="screen" style="position:fixed;left: 0;top: 0;background:#000;z-index:1000;"></div>') );
    
    $('#screen').css({"display": "block", opacity: 0.7, "width":$(window).width(),"height":$(window).height()});
    $('#ad-center').css({"display": "block"});
    $('#ad-center').css({"left": Math.round(($(window).width() - $('#ad-center').width())/2) +'px',"top": Math.round(($(window).height() - $('#ad-center').height())/2) +'px'});
    
  
    $('#screen').click(function() {R29.ads.welcome.close()});
    
    setTimeout(R29.ads.welcome.close, 1000*timeout_sec);
  },
  close: function () {
    $('#screen').remove();
    $('#ad-center').remove();
  }

}


/************************************************
*
*  Coooookkiiiee 
*
************************************************/

R29.cookie = {
  domain: (m=document.domain.match(/\.(refinery29\.com|stage\.refinery29\.net|dev\.refinery29\.net)$/))?m[0]:document.domain,
  set: function(name,value,seconds) {
  
    if (seconds == -1) {
      //-1 means keep it FOREVER (aka ~7 years, let's hope you get a new computer by then)
      seconds = 3600*24*365*7;
    }
    
    if (seconds) {
      //We got a permanent cookie
      var date = new Date();
      date.setTime(date.getTime()+(seconds*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else {
      //We got a session cookie
      var expires = "";
    }
    
    document.cookie = name+"="+value+expires+";path=/;domain=" + R29.cookie.domain + ";";
    
  },
  get: function (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;
  },
  remove: function(name) {
   this.set(name,"",-1);
  }
}

/************************************************
*
*  Slideshow 
*
************************************************/

R29.slideshow = {
  init: function ( details ) {
  
    details.img_cont.attr('curr-index', details.curr_index);
    
    details.img_cont.attr('locked', 0);
    
    var i = 0;
    
    var preload_imgs = [];
    
    //Get all the thumbnails
    
    $('a', details.thumb_cont).each( function() {
      
      var img_src  = details.imgs[i][0];
      var img_desc = details.imgs[i][1];
      
      //Add target to preloader
      preload_imgs[i] = img_src;
      
      //Set custom attibutes to the thumbnails.
      $(this).attr('full-src',  img_src);
      $(this).attr('full-desc', img_desc);
      $(this).attr('img-index', i);
      
      //Attach an action on click
      $(this).click(function(){
        R29.slideshow.setIndex($(this).attr('img-index'), details);
        
        //Except for the one clicked on
        //$(this).addClass('active');
        
        return false;
      });
      i++;
    })
    
    R29.image.preLoad(preload_imgs);
    
    R29.slideshow.setIndex(details.curr_index, details);
    
  },
  setIndex: function ( index, details ) {
  
    index = index * 1;
    
    if (details.img_cont.attr('locked') == 1) {
      return;
    }
    
    details.img_cont.attr('locked', 1);
  
    if (typeof details.imgs[index] == 'undefined') {
      index = 0;
    }
    
    var img_src  = details.imgs[index][0];
    var img_desc = details.imgs[index][1];
    
    //Make all thumbnails inactive..
    $('a', details.thumb_cont).removeClass('active');
    
    //Make the one with img-index=index active
    $('a[img-index=' + index + ']', details.thumb_cont).addClass('active');
    
    //Lets switch out.
    details.img_cont.attr('src', img_src);
    details.desc_cont.html(img_desc);
    details.img_cont.attr('curr-index', index);
    
    //Hide prev
    if (details.img_cont.attr('curr-index') == 0 ) {
      details.prev_button.hide();
    } else {
      details.prev_button.show();
    }
    
    //Hide next
    if (details.img_cont.attr('curr-index') >= (details.imgs.length - 1) ) {
      details.next_button.hide();
    } else {
      details.next_button.show();
    }
    
    $('a', details.prev_button).unbind('click').click(function() { R29.slideshow.setIndex(index-1, details);return false;});
    $('a', details.next_button).unbind('click').click(function() { R29.slideshow.setIndex(index+1, details);return false;});
    
    details.onChange( index );
    
    details.img_cont.attr('locked', 0);
    
  }
  
};


/************************************************
*
*  URL Functions 
*
************************************************/

R29.util = {
  inFrame: (window.location != window.parent.location) ? true : false
};

/************************************************
*
*  URL Functions 
*
************************************************/

R29.url = {};

R29.url.param = {
  parse: function ( param_str ) {
    
    if (!typeof param_str != 'string') {
      return {};
    } 
    
    var parts = param_str.split('&');
    var vars  = {};

    for(var i = 0; i < parts.length; i++) {
      var hash = parts[i].split('=',2);
      if (hash.length == 2)
        vars[unescape(hash[0])] = unescape(hash[1]);
    }
    
    return vars;
    
  },
  build: function ( params ) {
    var out = [];
    
    for( var k in params ) {
      out.push( escape(k) +'=' + escape(params[k]));
    }
    
    return out.join('&');
  },
  get: function() { 
  
    if (window.location.href.indexOf('?') < 1)
      return {};
    
    var e = window.location.href.indexOf('#');
    
    if (e < 1) {
      e = window.location.href.length;
    }
    
    return window.location.href.slice(window.location.href.indexOf('?') + 1,e);
  },
  getVars: function() {
    return R29.url.param.parse(R29.url.param.get());
  },
  getVar: function (key) {
    var params = R29.url.param.getVars();
    if (typeof params[key] != 'undefined')
      return params[key];
  }
}

R29.url.hash = {
  
  //
  // Get the value of everything after the #
  //
  get: function() {
  
    var parts = window.location.href.split('#', 2);
    
    if (parts.length == 1)
      return '';
    
    return unescape(parts[1]);
    
  },
  set: function (hash) {
    document.location = document.location.href.split('#')[0] + '#' + escape(hash);
  },
  getVars: function () {
  
    var parts = R29.url.hash.get().split('/');
    var vars  = {};
    
    for(var i = 0; i < parts.length; i++) {
    
      var hash = parts[i].match(/^([^\-]+)\-(.*)$/i);
      
      if (hash && hash.length == 3)
        vars[unescape(hash[1])] = unescape(hash[2]);
    }
    
    return vars;
  },
  getVar: function ( varname ) {
    var vars = R29.url.hash.getVars()
    
    if (typeof vars[varname] != 'undefined') 
      return vars[varname];
  },
  setVar: function ( varname, value) {
    var out = R29.url.hash.getVars();
    out[varname] = value;
    R29.url.hash.setVars(out);
    return R29.url.hash;
  },
  setVars: function ( hash ) {
  
    var out = [];
    
    for( var k in hash ) {
      out.push( escape(k) +'-' + escape(hash[k]));
    }
    
    R29.url.hash.set(out.join('/'));
  
  },
  hashVar: function ( varName, value ) {

    if (typeof value != 'undefined') {
      return R29.url.hash(varName + '-' + value);
    }

    var parts = R29.url.hash().split('-', 2);

    if (parts.length == 1)
      return;

    return parts[1];
  }

}

/************************************************
*
*  Cache, I needs it. 
*
************************************************/

R29.cache = {
  get: function(key) {
    if ( typeof R29.cache._cache_bin[key] !='undefined') {
      return R29.cache._cache_bin[key];
    }
    return null;
  },
  set: function(key, value) {
    R29.cache._cache_bin[key] = value;
  },
  _cache_bin: {}
}
 
 
/************************************************
*
*  Our API is all up in yos face.
*
************************************************/

R29.api = {
    baseUrlLocal:  '/api',
    baseUrlRemote: null,
    isRemote:      null, 
    setServer:     function() {
    
      if (document.domain.match(/\.refinery29.com$/)) {
        //We're in production
        R29.api.isRemote   = false;
        R29.api.baseUrlRemote = document.location.protocol + '//api.refinery29.com';
      } else if (m = document.domain.match(/(([a-z0-9]+)\.)?(dev|stage).refinery29.net$/)) {
        //We're in dev/stage
        R29.api.isRemote   = false;
        R29.api.baseUrlRemote = document.location.protocol + '//' + (m[3]=='stage'?'api.stage.refinery29.net':'api.'+m[2]+'.dev.refinery29.net');
      } else {
        //Someone else is including us.
        R29.api.isRemote   = true;
        R29.api.baseUrlRemote = document.location.protocol + '//api.refinery29.com';
      }

    },
    ajax: function (url, method, data, cb, cb_err, settings) {
    
      if (typeof settings == 'undefined')            settings = [];
      if (typeof settings.cache == 'undefined')      settings.cache = false;
      if (typeof settings.isRemote == 'undefined')  settings.isRemote = R29.api.isRemote;
      
      var data_type = 'json';
      var api_url   = R29.api.baseUrlLocal + url;
      var out_cb    = cb;
      var out_cb_err = cb_err;
      
      //Or if we're doing jsonp
      if (settings.isRemote == true) {
        data_type = 'jsonp';
        api_url   = R29.api.baseUrlRemote + url;
        data.method = method;
        method    = 'GET';
        out_cb_err = function() {}; //No error handling in jsonp
        out_cb = function (r) {
        
          if (r.status == 'OK') {
            cb(r.payload);
          } else {
            cb_err(r.payload);
          }
          
        }
        
      } else {
        //In case of an error, let's wrap it in a function that returns a the error message.
        out_cb_err = function(r) {
          return cb_err(jQuery.parseJSON(r.responseText));
        };
      }
      
      return $.ajax({
        url:      api_url, 
        data:     data, 
        cache:    settings.cache,
        type:     method,
        success:  out_cb,
        error:    out_cb_err,
        dataType: data_type
      });
 
    },
    _post: function ( url, data, cb ) {
      return R29.api.ajax(url,'POST', data, cb );
    },
    _get: function ( url, data, cb, cb_err,isRemote, cache ) {
      return R29.api.ajax(url,'GET', data, cb,cb_err, isRemote, cache);
    },    
    _put: function ( url, data, cb ) {
      return R29.api.ajax(url,'PUT', data, cb );
    },
    _delete: function ( url, data, cb ) {
      return R29.api.ajax(url,'DELETE', data, cb );
    }
};

R29.api.setServer();

/************************************************
*
*  Fancy ass search, uses jsonp for extra speed. 
*
*   Example: R29.search.entry({query:'cat'}, function(r) {console.log(r)});
*
************************************************/

R29.search = {
  entry: function ( params, cb) {
    return R29.api._get('/search/entry', params, cb, null, true, false);    
  }
}

/************************************************
*
*  Blog objects
*
************************************************/

R29.blog = {
  base_url: '/blog',
  
  //Gets a list of tags ordered by popularity
  
  tags: function (query, cb) {
    return R29.api._get(R29.blog.base_url + '/tags', {search:query}, cb, null, true, false);    
  }
}

/************************************************
*
*  Subscribe and find the closest lists 
* 
*   Examples: 
*       R29.mailinglist.subscribe( 'jorge+three@refinery29.com', ['main_new_york'],function(r) { console.log(r); });
*       R29.mailinglist.closest( 0, function(r) { console.log(r); });
*
************************************************/

R29.mailinglist = {
  closest: function ( threshold_miles, cb, cb_err) {
    if ( !threshold_miles > 0) {
      threshold_miles = 0;        
    }
    return R29.api._get('/mailinglist/closest', {threshold: threshold_miles}, cb, cb_err); 
  },
  subscribe: function ( email, lists, cb, cb_err) {
    //Yeah yeah, I know it's supposed to be a POST but PHP is being an ass
    return R29.api._post('/mailinglist/subscribe', {email: email, lists: lists}, cb, cb_err); 
  }
}

/************************************************
*
*  Loader class to load external files 
*
*   Example: R29.loader.css('/path/to/file.css');
*
************************************************/

 
R29.loader = {
  static_base: "static.refinery29.com",
  static: {
    file: function(file) {
      return document.location.protocol + '//' + R29.loader.static_base + file;
    },
    css: function(file) {
      return R29.loader.css(R29.loader.static.file(file));
    }
  },
  css: function(file){
	  $('head').append('<link href="' + file + '" type="text/css" rel="stylesheet" />');
  }
};
 
  
/************************************************
*
*  Widget the world wattcherrrr 
*
************************************************/  

R29.widget = {};
  
R29.widget.clickaway = function() {

  $("input.clickaway").each(
    function() {

      //So we don't call this twice on each one.
      if ($(this).attr('clickaway')) 
        return;
      
      $(this).attr('clickaway',1);
      if ($(this).val().length==0) {
        $(this).val($(this).attr("default")).addClass("disabled");
      }
      
      $(this).focus(
        function() {
          if ($(this).hasClass('disabled') || $(this).val() == $(this).attr("default")) {
            $(this).val("").removeClass("disabled"); 
          }
        }
      ).blur(
        function() {
          if ($(this).val().length==0) {
            $(this).val($(this).attr("default")).addClass("disabled");
          }
        }
      )
    }
  );  
}

//Call this guy on ready.
$().ready(R29.widget.clickaway);

/************************************************
*
*  Think the cat below, but with a signup form
*
*         |\__/,|   (`\
*       _.|o o  |_   ) )
*  ---(((---(((---------
*
************************************************/ 

//Delay in ms before we show the thing
R29.widget.signupDelay = 1000;

R29.widget.signup = function() {
  
  //Yes, busted in IE
  if ($.browser.msie) return false;
  
  //Bad ipad, bad
  if (navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/)) return false;
  
  if (R29.cookie.get("signup-ws")) return false;
  
  //This needs a CSS file, so, let's grab it.
  R29.loader.static.css('/base/widgets/signup-ws/style.css');
  
  //Draw the actual divs

  $('body').append(
    '<div id="signup-ws" style="height:0;position:fixed;bottom:0;">' + //This is a good location so it's hidden from the start
    ' <div class="x"></div>' +
    ' <div class="trans"></div>' +
    ' <div class="inner">' +
    '  <div class="market-text"></div>' +
    '  <input type="text" class="clickaway email" value="" default="Your Email Address" name="" />' +
    '  <input class="submit" type="submit" value="GO" />' +
    ' </div>' +
    '</div>'
  );
  
  R29.widget.clickaway();
  
  //X to close
  $("#signup-ws div.x").click (
    function() {
      R29.cookie.set("signup-ws", 1, 3600*24*7); //Set a cookie for a week.
      $("#signup-ws").animate({height:"0px"});
    }
  );
  
  //Grab the closest mailing list, if one, and set to subscribe the user.
  R29.mailinglist.closest( 50, 
    function (r) {
    
      list_ids = ["mail_everywhere"];
      
      if (r.length) {
        list_ids[1] = r[0].list_id;
        $("#signup-ws .market-text").addClass(r[0].market);
      }
    
      //Wait for DOM ready and show the thing
      $().ready(function() {
        $("#signup-ws").show().delay(R29.widget.signupDelay).animate({height:"40px"}, 500);
      });
      
      $("#signup-ws .submit").click( 
        function() {
      
          //If the box is empty or set to disabled
          if ($("#signup-ws .email").val().length==0 || $("#signup-ws .email").hasClass("disabled")) return false;
          
          R29.cookie.set("signup-ws", 1, -1); //You'll never see this again!
          
          if (!R29.validate.email($("#signup-ws .email").val())) {
            $("#signup-ws .email").val('Invalid Email').addClass('disabled');
            return;
          }
           
          //Do the actual subscription
          
          R29.mailinglist.subscribe( $("#signup-ws .email").val(), list_ids, function(r) { 
          
            $("#signup-ws .inner").fadeOut(400,function() {
              $("#signup-ws .trans").addClass("confirmation");
            });
            
            $("#signup-ws .email").val('Thanks!').addClass('disabled');
            $("#signup-ws").delay(4000).animate({height:"0px"});
            
          },
          function(r) {
            
          });
          
          return false;
        }
      );
    }
  );
  
  return true;
};

/***********************************************
*
*  I VALIDATE 
*
*************************************************/

R29.validate = {
  email: function(email) {
    //You and me both know email validation is a sham
    return email.match(/^(.*)@(.*)\.(.*)$/)?true:false;
  }
}
