// functions and what not

var imgjson, image_library, placejson, place_library;
var loader = $('#loader');
var board_count = 15;
var page = 1;
var loading_content = false;
var tweet_array = new Array();


// ie8 indexOf fix
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0), j = this.length; i < j; i++) {
      if (this[i] === obj) { return i; }
    }
  return -1;
  }
}

// get obj size
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// escape HTML chars
var entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
};

function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
}


// format money
Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

// no console support fix
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };

// show user message bar
function show_um(msg_txt, msg_type, url){
  var um = $('#user-messages');
  um.stop().hide().css({'bottom':'-60px'}).removeClass().addClass(msg_type).html(msg_txt).show().animate({ 'bottom': '0px' }, 300, 'easeOutQuint', function(){
    um.delay(4000).animate({ 'bottom':'-60px'}, 300, 'easeOutQuint', function(){
	  if(url) window.location = url;
	});	
  });
}

// show user choice dialog
function show_uc(msg_txt, url){
	var uc = $('#user-choice');
	uc.show().html(msg_txt + '<div class="uc-links"><a href="'+url+'">Yes</a> <a href="#" id="close-uc">Cancel</a></div>').css({ 'margin-top' : '-'+(($('#user-choice').height()+80)/2)+'px' });
}

// get image library list
function get_image_library(){
  if(store.get("image_library")) imgjson = store.get("image_library");
  if(!imgjson) imgjson = { "images": [] };
}

function get_place_library(){
  if(store.get("place_library")) placejson = store.get("place_library");	
  if(!placejson) placejson = { "places": [] };
}

// show library section
function show_library(sec, tab){
  $('.library-section').hide();
  $('#'+sec).show();
  $('#library .tabs a').removeClass('active');
  $('#'+tab).addClass('active');
  $('.clear-btn').hide();	
  $('#clear-'+sec).show();
}

// replace query value function
function replaceQueryString(url,param,value) {
  var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
  if (url.match(re)){
    return url.replace(re,'$1' + param + "=" + value + '$2');
  }else{
	  if(url.indexOf('?') > -1){
		  return url + '&' + param + "=" + value;
	  }else{
		  return url + '?' + param + "=" + value;
	  }
  }
}

// ajax email
function send_email(to, type, data){
  $.post(site_url+'/wp-content/themes/little/emailer.php', { to:to, type:type, data:data });
}

// like a canvas
function like_canvas(){
  board_id = $('input[name=board_id]').val();
  user_ip = $('input[name=user_ip]').val();
  $.post(site_url+"/wp-content/themes/little/save.php", { mode: 'like', boardid: board_id, userip: user_ip, type: 'board'}, function(data){ 
    if(data == 'OK'){ 
	  show_um('Thanks for loving this!', 'add');
	  var likes = 0;
	  likes = parseInt($('#like-board em').text());
	  //console.log(likes);
	  likes++;
	  $('#like-board').html('<div class="like-in"><span>3</span><em>'+likes+'</em></div><div class="like-txt">You love this!</div><div class="clear"></div>').removeClass('rdy').removeAttr('onlick');
	}else{
	  show_um(data, 'error');
	}
  });	
}

function load_currency(amount,currency,local){
	$('#total').html('Loading...');
	$.ajax({
		type: "POST",
		url: "http://mylittlestylefile.com/misc/currency.php",
		data: { 
			a: amount, 
			c: currency, 
			l: local 
		}
	}).done(function( data ) {
		//var e = data.split(",");
		var num = Number(data.replace(/[^0-9\.]+/g,""));
		var ftd = num.formatMoney(2, '.', ',');
		$('#total').html('<h2>'+ftd+' '+local+'</h2>');
	});
}

// add to canvas view count
function viewed_canvas(){
  board_id = $('input[name=board_id]').val();
  user_ip = $('input[name=user_ip]').val();
  $.post(site_url+"/wp-content/themes/little/save.php", { mode: 'view', boardid: board_id, userip: user_ip, type: 'board'}, function(data){ });
}

// clear pin library
function clear_library(type){
  if(confirm('Are you sure you want to clear your '+type+' library?')){
    if(type == 'images'){
	  $('#image-library .pin-img').each(function(){ $(this).remove() });
	  store.set("image_library", "");
	  imgjson = '';	
	  $('#clear-image-library').hide();
	}else{
	// assume place
	  $('#places-library .pin-place').each(function(){ $(this).remove() });
	  store.set("place_library", "");
	  placejson = '';
	  $('#clear-places-library').hide();
	}
  }
}


// ajax pagination
function load_more_boards(sort_val){
	
	if(!loading_content){
	
	loading_content = true;
	
	start_count = (page * board_count);
	end_count = (start_count + board_count);
	
	$.ajax({
  		url: site_url + '/wp-content/themes/little/load-more.php',
  		data: { start: start_count, end: end_count, sorting: sort_val },
  		method: 'get',
  		success: function(data) {
   			$('#more-boards').append(data);
    		//console.log('Load was performed.');
			page++;
			loading_content = false;
  		}
	});
	
	}
}

// get url vars
$.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
      return vars;
    },
    getUrlVar: function(name){
      return $.getUrlVars()[name];
    }
});

// jquery magic time! let's begin...
$(function(){
	
  // news slider
  $('#news-items').cycle({
    timeout: 0,
	fx: 'scrollHorz',
	next: '#next-news',
	prev: '#prev-news'
  });
	
  // hero slider
  $('#heroes').cycle({
    timeout: 9000,
    fx: 'fade',
    pager:  '#hero-nav',
	pagerAnchorBuilder: function(idx, slide) { 
		sec = $(slide).attr('data-sec');
        return '<a href="#" class="'+sec+'">' + idx + '</a>'; 
    } 
  });
  
  if($('.hero').length>1){
	$('#hero-nav').show();  
  }
  
  // home articles slider
  $('.polaroid .home-articles').each(function(i){
	  if($('.home-article-wrap', this).length > 1){
	  	$(this).after('<div class="article-nav article-nav'+i+'">').cycle({
            fx:     'fade',
            timeout: p_timeout,
            speed: p_speed,
            delay: (p_delay*i),
            after: onAfter,
            pager:  '.article-nav' + i
        });
	  }
  });
  
  function onAfter(){
  	  
  }
  
  //show/hide login/rego panel
  var opened = false;
  
  $('#user-login-reg:not(.loggedin), #logged-out, #logged-out-p').click(function(){
	 if(!opened){
	   $('#user-panel').stop().animate({ 'top': '0px' }, 400, 'easeInOutQuad'); 
	   $('#user_login').focus();
	   opened = true;
	 }else{
	   $('#user-panel').stop().animate({ 'top': '-200px' }, 400, 'easeInOutQuad'); 
	   opened = false;
	 }
	 return false;
  });
  
  $('html').click(function() {
	 $('#user-panel').stop().animate({ 'top': '-200px' }, 400, 'easeInOutQuad'); 
	 $('#submit-listing').fadeOut(300);
	 opened = false;
  });

  $('#user-panel, #logged-out ,#request-listing, #submit-listing:not(#submit-listing #dk_container_company_channel)').click(function(event){
     event.stopPropagation();
  });

  // twitter
  $('.tw-share-btn').click(function(){
	 post_url = $(this).attr('data-url');
	 status = $(this).attr('data-title');
	 mlsf_url = "http://mylittlestylefile.com";
	 window.open("http://twitter.com/intent/tweet?"+mlsf_url+"&text="+status+" - &url="+post_url+"&via=littlestylefile","Twitter","width=820,height=475");
	 return false; 
  });
  // facebook
  $('.fb-share-btn').click(function(){
	 post_url = $(this).attr('data-full');
	 post_img = $(this).attr('data-img');
	 post_title = $(this).attr('data-title');
	 post_desc = $(this).attr('data-desc');
	 window.open("http://www.facebook.com/share.php?s=100&p[title]="+post_title+"&p[url]="+post_url+"&p[images][0]="+post_img+"&p[summary]="+post_desc,"Facebook","width=820,height=475");
	 return false; 
  });
  // google
  $('.gp-share-btn').click(function(){
	 post_url = $(this).attr('data-full');
	 window.open("https://plus.google.com/share?url="+post_url,"Google+","width=820,height=475");
	 return false; 
  });
 // pintrest
  $('.pin-share-btn').click(function(){
   	 post_url = $(this).attr('data-full');
	 post_img = $(this).attr('data-img');
	 window.open("http://pinterest.com/pin/create/button/?url="+post_url+"&media="+post_img,"Pintrest","width=820,height=475");
	 return false; 
  });

  
  //placeholder support
  $('[placeholder]').placeholder();
 
  
  // pretty select dropdowns
  
  
  $('#stockist-search select').dropkick({
    change: function (value, label) {
     /*  $('#section-search form').submit(); */
    }
  });
  
  $('#results-filter select[name=sort]').dropkick({
    change: function () {
      purl = window.location.href;
	  para = 'order'
      nu = replaceQueryString(purl,para,this.value);
	  window.location = nu;
    }
  });
  
  $('#results-filter select[name=channel]').dropkick({
    change: function () {
      purl = window.location.href;
	  para = 'channel'
      nu = replaceQueryString(purl,para,this.value);
	  window.location = nu;
    }
  });
  
  $('#board-bar select, #contributor-bar select').dropkick({
    change: function () {
	  purl = window.location.href;
	  para = 'sort'
      nu = replaceQueryString(purl,para,this.value);
	  window.location = nu;
    }
  });
  
  $('#image-library select').dropkick({
    change: function () {
	  if(this.value == 'all'){
		 $('.pin-img').show(); 
	  }else{
	    $('.pin-img').hide();
        $(".pin-img[data-cat='"+this.value+"']").show();
	  }
    }
  });
  
  $('#places-library [name=pins]').dropkick({
    change: function () {
      if(this.value == 'Type') return;
	  if(this.value == 'all'){
		 $('.pin-place').show(); 
	  }else{
	    $('.pin-place').hide();
        $(".pin-place[data-place='"+this.value+"']").show();
	  }
    }
  });
  
  $('#places-library [name=regs]').dropkick({
    change: function () {
      if(this.value == 'Region') return;
	  if(this.value == 'all'){
		 $('.pin-place').show(); 
	  }else{
	  
	    $('.pin-place').hide();
	    $(".pin-place[data-region*='"+this.value+"']").show();
	  }
    }
  });
  
  $('#currency-options').dropkick({
    change: function () {
        var a = $('#amount').val(); 
    	var c = this.value;
    	var l = $('#local').val();
        load_currency(a,c,l);
    }
  });
  
  $('[name=company_channel]').dropkick({
    change: function () {
      
    }
  });
  
  $('.mlsf-forms select').dropkick({
    change: function () {
      
    }
  });
 
  
  
  // tooltips
  $('.tips').tipsy({gravity: 's', opacity: 1});
  $('.miniColors-trigger:nth-child(2)').tipsy({live: true, gravity: 's', fallback: "Background colour", opacity: 1});
  $('.miniColors-trigger:nth-child(3)').tipsy({live: true, gravity: 's', fallback: "Text colour", opacity: 1});
  $('#share-board,#image-board').tipsy({gravity: 's', opacity: 1});
  $('.board .pin-img:not(.other-user.board .pin-img), .moodboards .pin-img').tipsy({live: true, gravity: 's', fallback: "Click to add to Inspiration Board", opacity: 1});
  $('.remove-pinned:not(.board .remove-pinned)').tipsy({live: true, gravity: 's', fallback: "Remove image", opacity: 1});
  $('.view-article:not(.board .view-article)').tipsy({live: true, gravity: 's', fallback: "View article", opacity: 1});
  $('.pin-me[data-type=images]').tipsy({live: true, gravity: 's', fallback: "Save this image", opacity: 1});
  $('.pin-me[data-type=places]').tipsy({live: true, gravity: 's', fallback: "Save this place", opacity: 1});
	
  // add pin to library
  $('.pin-me').click(function(){  
	
    // check type
    pin_type = $(this).attr('data-type');
	
		
    if(pin_type == 'images'){
		
	   get_image_library();	
	   
	    // grab image data
	    full_url =  $(this).parent().find("img").attr('data-image');
	    pin_url = $(this).parent().find("img").attr('data-pin');
	    img_cat =  $(this).parent().find("img").attr('data-cat');
        img_id = $(this).parent().find("img").attr('data-id');
		article_url = $(this).parent().find("img").attr('data-url');
		article_id = $(this).parent().find("img").attr('data-post');
		//shelf_url = $(this).parent().find("img").attr('data-shelf');
		details = $(this).parent().find("img").attr('data-details');
		
	   imagelibrary = JSON.stringify(imgjson);
	  
      if(imagelibrary.indexOf(img_id) == -1){
	    
	    // add them to sidebar library
	    $('#image-library').append('<div class="pin-img" data-id="'+img_id+'" data-full="'+full_url+'" data-cat="'+img_cat+'" data-url="'+article_url+'" data-post="'+article_id+'" data-details=\''+escapeHtml(details)+'\'><img src="'+pin_url+'" /><div class="view-article">i</div><div class="remove-pinned">.</div></div>');
	    	
		// add to object
		imgjson.images.push({ 
			"pin_url": pin_url, 
			"full_url": full_url, 
			"id": img_id, 
			"cat": img_cat, 
			"article": article_url, 
			"article_id": article_id,
			"details" : details 
		});
		
		// save updated object
		store.set("image_library", imgjson);
		
		var collection_id = $('#collection-modal').attr('data-collection');
		
		console.log(collection_id);
		
		if(collection_id){
			$.post(site_url+"/wp-content/themes/little/ajax-collections.php", { mode: 'update_pins', collectionid: collection_id, userid: user_id, pins: JSON.stringify(imgjson)  }, function(data){ 
				if(data == 'updated'){ 
					//show_um('The image has been added to your collection', 'add');
				}else{
					//show_um(data, 'error');
				}
			});
		}

	    // show confirm msg
		show_um('The image has been added to your library', 'add');
		// show in library
		show_library('image-library', 'images-tab');
	  }else{
	    // already added
		show_um('You have already added this image to your image library!','error');
	  }	
	  	
    }else{
		
     get_place_library();		
	 
	 // grab place data	
	 place_id = $(this).attr('data-id');
	 place_location = $(this).attr('data-location');
	 place_type = $(this).attr('data-place');
	 place_title = $(this).attr('data-title');	
	 place_url = $(this).attr('data-url');
	 place_region = $(this).attr('data-region');
	 
	 placelibrary = JSON.stringify(placejson);
	 
	 if(placelibrary.indexOf(place_id) == -1){
		
	  // add them to sidebar library
	  $('#places-library').append('<div class="pin-place" data-id="'+place_id+'" data-location="'+place_location+'" data-place="'+place_type+'" data-url="'+place_url+'" data-region="'+place_region+'"><span>'+ place_title +'</span><div class="view-article">i</div><div class="remove-pinned">.</div></div>'); 
	  // add to object
	  placejson.places.push( { "title": place_title, "location": place_location, "id": place_id, "place_type": place_type, "place_url": place_url, "place_region": place_region } );	
	  // save updated object
	  store.set("place_library", placejson);
	  // show confirm msg
	  show_um('The place has been added to your library', 'add'); 
	 // show in library
	  show_library('places-library', 'places-tab');
	 }else{
		// already added
		show_um('You have already added this place to your places library!','error'); 
	 }
			
    }
	
  });
  
  // view article associated with pin
  $('#image-library, #places-library, .pins .pin-img').on("click", ".view-article", function(){
  	var pin_link = $(this).parent().attr('data-url');
  	if(moved){
	  notlink = true;
	  show_uc('You have attempted to leave this page. If you have added or made any changes without saving, everything will be lost. <br /> Are you sure you want to leave this page?', pin_link);
	  return false;
	}else{
  		window.location = pin_link;
  	}
  });
  
  // remove pin from library
  $('#image-library, .pins .pin-img').on("click", ".remove-pinned", function(){
  
	if(confirm("Are you sure you want to delete this?")){
	  	$('.tipsy').remove();
		$('#clear-image-library').show();
		var img_id = $(this).parent().attr('data-id');
		get_image_library();
		// delete from object
	    for (var i=0; i<imgjson.images.length; i++) {
	      if (imgjson.images[i].id == img_id) {
		    imgjson.images.splice(i,1);
	      }
		}
			
		var collection_id = $(this).parent().attr('data-collection');
		
		$.post(site_url+"/wp-content/themes/little/ajax-collections.php", { mode: 'update_pins', collectionid: collection_id, userid: user_id, pins: JSON.stringify(imgjson)  }, function(data){ 
			if(data == 'updated'){ 
				//show_um('The image has been deleted from your collection', 'error');
			}else{
				//show_um(data, 'error');
			}
		});

		// save updated object
		store.set("image_library", imgjson);
		// remove from sidebar library
		$(this).parent().remove();
		// show confirm msg
		show_um('Image deleted from your library!','error');
	}
  });
  
  $('#places-library').on("click", ".remove-pinned", function(){
  
  	if(confirm("Are you sure you want to delete this?")){
  
	  	$('.tipsy').remove();
		var place_id = $(this).parent().attr('data-id');
		get_place_library();
		// delete from object
	    for (var i=0; i<placejson.places.length; i++) {
	      if (placejson.places[i].id == place_id) {
		    placejson.places.splice(i,1);
	      }
		}
		// save updated object
		store.set("place_library", placejson);
		// remove from sidebar library
		$(this).parent().remove();
		// show confirm msg
		show_um('Place deleted from your library!','error');
	}
  });
  
  // get pinned images
  get_image_library();
  if(imgjson){
    for (var i = 0; i < imgjson.images.length; i++) { 
	  img_id = imgjson.images[i].id;
	  full_url = imgjson.images[i].full_url;
	  pin_url = imgjson.images[i].pin_url;
	  img_cat = imgjson.images[i].cat;
	  //shelf_url = imgjson.images[i].shelf;
	  article_url = imgjson.images[i].article;
	  article_id = imgjson.images[i].article_id;
	  details = imgjson.images[i].details;
	  
      $('#image-library').append('<div class="pin-img" data-id="'+img_id+'" data-full="'+full_url+'" data-cat="'+img_cat+'" data-url="'+article_url+'" data-post="'+article_id+'" data-details=\''+escapeHtml(details)+'\'><img src="'+pin_url+'" /><div class="view-article">i</div><div class="remove-pinned">.</div></div>');
    }
  }
  
  //get pinned places
  get_place_library();
  if(placejson){
    for (var i = 0; i < placejson.places.length; i++) { 
	  place_id = placejson.places[i].id;
	  place_location = placejson.places[i].location;
	  place_title = placejson.places[i].title;
	  place_type = placejson.places[i].place_type;
	  place_url = placejson.places[i].place_url;
	  place_region = placejson.places[i].place_region;
      $('#places-library').append('<div class="pin-place" data-id="'+place_id+'" data-location="'+place_location+'" data-place="'+place_type+'" data-url="'+place_url+'" data-region="'+place_region+'"><span>'+ place_title +'</span><div class="view-article">i</div><div class="remove-pinned">.</div></div>'); 
    }
  }
  
  // library tabs
  $('#library .tabs a').click(function(){
	 sec = $(this).attr('data-section');
	 tab = $(this).attr('id');
	 show_library(sec, tab);
	 return false; 
  });
  
  //moodboards

  if($('#canvas').length>0){  
    $('.pin-img img').click(function(){ 
		
		var item_loc = $(this).parent().attr('data-full');
		var item_url = $(this).parent().attr('data-url');
		var item_id = $(this).parent().attr('data-post');
		
		var item_data = $(this).parent().attr('data-details');
		
	    insert_image(item_loc, item_url, item_id, item_data);	  
    });
  }
  
  // directory accordion
  $('.listing').on("click", ".list-head", function(){	
    if(!$(this).siblings('.list-content').hasClass('open-me')){
	  // hide opened listing
	  $('.open-me').slideUp(200, 'easeInOutQuad').removeClass('open-me');
	  $('.list-head').removeClass('active');
	  // show this listing
	  $(this).siblings('.list-content').slideDown(200, 'easeInOutQuad').addClass('open-me'); 
	  $(this).addClass('active');
	}else{
	  $('.open-me').slideUp(200, 'easeInOutQuad').removeClass('open-me');	
	  $('.list-head').removeClass('active');
	}
  });
  
  // directory pagination
  $('#directory-pag a').click(function(){
	 $('#directory-pag a').removeClass('selected');
	 $(this).addClass('selected');
	 list_class = $(this).attr('data-class');
	 $('.listing').hide();
	 $('.'+list_class).show();
	 return false; 
  });
  
  //colorpicker
  if($('#color-selector').length>0){
  $('#color-selector').minicolors({
    change: function(hex, rgb){ 
		set_canvas_bg(hex);
	}
  });
  }
  
  // print page
  
  $('.post-socials .print-day').on('click', function(e){
	  window.print();
	  e.preventDefault();
  });
  
  // text tools
  $('.text-btn').click(function(){
	  $(this).toggleClass('on');
  });
  
  // icons show tab
  $('#pin-tool').click(function(){
	  show_library('image-library', 'images-tab');
  });
  
  $('#place-tool').click(function(){
	  show_library('places-library', 'places-tab');
  });
  
  // select share link
  $("#share-board [type=text], #image-board [type=text]").focus(function(){
      this.select();
  });
  
  //open user board
  $('#main, aside').on("click", ".board", function(){
	  bid = $(this).attr('data-id');
	  bk = $(this).attr('data-key');
	  bt = $(this).attr('data-type');
	  if(bk){
	    window.location = home_url+'/board/'+bid+'/'+bk;
	  }else{
	    window.location = home_url+'/board/'+bid;	  
	  }
  });
  
  // switch contributor content
  $('.switch-content-data').on('click', function(e){
	  $(this).parent().toggleClass('swap');
	  e.preventDefault();
  });
  
  // focus on search
  $('#search-focus').click(function(){
	 window.scrollTo(0, 0);
	 $('#search input[type=text]').focus().stop().animate({'width': '282px'},850, 'easeInOutQuad');
	 $('#search').stop().animate({'width': '330px'},850, 'easeInOutQuad');
	 return false;
  });
  
  
  // tabs
  $('#feature-tabs a').click(function(){
	 tab = $(this).attr('data-tab');
	 $('.tab-section').hide();
	 $('#'+tab).show();
	 $('#feature-tabs a').removeClass().addClass('non-active');
	 $(this).removeClass().addClass('active');
	 return false;
  });
  	  
  // add target="_blank" to external links 
  $('a[href^="http://"]:not([href*="mylittlestylefile.com"])').attr('target','_blank');
  
  // project carousel
    $("#carousel").carouFredSel({
		direction			: "left",
		circular: true,
		infinite: true,
		auto 	: false,
		align: 'center',
		prev	: {	
			button	: "#prev-carousel",
			key		: "left"
		},
		next	: { 
			button	: "#next-carousel",
			key		: "right"
		},
		items		: {
			visible		: 4,
			width		: 175
		},
		scroll:  { 
			easing : "easeOutQuint",
			duration: 1000,
			x: 'scroll'
		},					
	});	
	
  // show current slide
  var top_x_id = $.getUrlVar('t');
  if(top_x_id){
		$("#carousel").trigger("slideTo", "#top-x-"+top_x_id);  
  }
  
  //moodboard bg load
  if($('#wrap .board').length>0){
    $('#wrap .board').each(function(){
      $('img', this).load(function(){
	    $(this).css({ 'background' : '#fff' });
	  });
    });
  }
  
  // close user choice dialog
  $('#user-choice').on("click", "#close-uc", function(){
    notlink = false;
  	$('#user-choice').hide();
  	return false;
  });
  
  // moodboard share links
  $('#share-as-link').click(function(){
  		$(this).addClass('active');
  		$('#share-as-image').removeClass('active');
	 	$('#share-board').show(); 
	 	$('#image-board').hide();
	 	return false;
  });
  
  $('#share-as-image').click(function(){
  		$(this).addClass('active');
  		$('#share-as-link').removeClass('active');
	 	$('#image-board').show(); 
	 	$('#share-board').hide();
	 	return false;
  });
  
  // youtubessssss
  if($('#ytplayer').length>0){
  var vid = $('#ytplayer').attr('data-video');
  var vw = $('#ytplayer').attr('data-width');
  var vh = $('#ytplayer').attr('data-height');
  $("#ytplayer").tubeplayer({
	width: vw, // the width of the player
	height: vh, // the height of the player
	allowFullScreen: "true", // true by default, allow user to go full screen
	initialVideo: vid, // the video that is loaded into the player
	preferredQuality: "hd720", // preferred quality: default, small, medium, large, hd720
	iframed: true,
	showControls: 1,
	modestbranding: false,
	wmode: 'transparent',
	onPlayerPlaying: function(id){ 
		$('#videos .bottom-panel').fadeOut(200);
		//console.log('PLAYING YO!');
	}, // after the play method is called
	onPlayerPaused: function(){
		//console.log('PAUUUUUSED');
	}, // after the pause method is called
	onPlayerEnded: function(){
		$('#videos .bottom-panel').fadeIn(200);	
	}, // after the player is stopped
	onSeek: function(time){}, // after the video has been seeked to a defined point
	onMute: function(){}, // after the player is muted
	onUnMute: function(){} // after the player is unmuted
  });
  }
  
  // vimeoooooos
  if($('#vimplayer').length > 0){
  var iframe = $('#vimplayer')[0],
      player = $f(iframe);
  
   player.addEvent('ready', function() {  
    player.addEvent('pause', onPause);
    player.addEvent('finish', onFinish);
    player.addEvent('playProgress', onPlayProgress);
  });
  
  function onPause(id) {
   //
  }

  function onFinish(id) {
    $('#videos .bottom-panel').fadeIn(200);	
  }

  function onPlayProgress(data, id) {
    $('#videos .bottom-panel').fadeOut(200);
  }
  }
  
  // Word count
  $('.word-counter').on('keyup', function(){
	 var regex = /\s+/gi;
	 var text = $(this).val(); 
	 var word_count = text.trim().replace(regex, ' ').split(' ').length;
	 $('.word-count').html(word_count + 'words');
  });
  
 
  	// Google places autocomplete 
 	var input = document.getElementById('location-field');
 	var options = {
 		componentRestrictions: {country: 'aus'}
	};
	if(input){
		autocomplete = new google.maps.places.Autocomplete(input, options);
	}
	
	// Show/hide form content
	$('.store-type input[name=listing_type_online]').on('change', function(){
		if($(this).is(':checked')){
			$('.shipping-regions').removeClass('hidden');
		}else{
			$('.shipping-regions').addClass('hidden');
		}
	});
 	
}); // end dat jquery readiness


// scroll listener
$(document).scroll(function(){ 
  // dock nav on scroll below view
  
  if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
	  // some code..
  }else{
  
  sch =  $(document).scrollTop();
  if(sch > 158){
	$('[role=main-navigation]').addClass('docked');
  }else{
    $('[role=main-navigation]').removeClass('docked');
  } 
  
  }
  
});

// window scroll listener
$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() == $(document).height()) {
    sort_value = $('[name=sort_value]').val();
	if($('#more-boards').length>0){
      load_more_boards(sort_value);
    }
  }
});

$(window).load(function(){
  // image masonry
  $('#grid-images').masonry({
    itemSelector: '.col-image'
  });
  
  $('#results').masonry({
    itemSelector: '.result'
  });
  
  $('#brand-logos').masonry({
    itemSelector: '.logo'
  });
  
});

//mouse move listener
$(window).mousemove(function(e){
  x=e.pageX;
  y=(e.pageY - $(window).scrollTop());
  $('#item-info-tip').css({ 'top': y, 'left': x });
});
