$().ready(function(){

/* Initial CSS Commands - for accessibility reasons */

	$('.pics').css({height: "500px"});
	$('body#product .product_box .product_image').css({height: "500px"});
    $('.slide-box-wrapper').css({width: "225px"});
    $('.associated_images').css({height: "auto", marginBottom: "20px"});
    //$('.associated-image-menu').css({opacity: "0", height: "100%", position: "absolute"})

	/* Dropdown re-usable codes */
	$('.dropdown ul .active').click(function(){
		$(this).parents('ul').toggleClass('show');
		return false;
	})
	
	$('.dropdown ul').click(function(){
		$(this).toggleClass('show');
	})
	
	
	$(document).click(function(e){
		elem = e.target;
		//alert($(elem).parents('.show').length)
		if($(elem).parents('.show').length == 0){
			$('.show').removeClass('show');
		}
	})
	
	$(document).click(function(e){
		elem = e.target;
		if($(elem).parents('.blind, .blink-link').length == 0){
			$('.blind').slideUp('10');
			$('.slider-link').removeClass('opened-slider');
		}
	})
	
	$('.more-categories a').click(function(e){
		$('.f-block').toggleClass('show');
	})
	
	$('.f-block').mouseleave(function(){
		$(this).removeClass('show')
	})

	/* Collapse re-usable codes */
	$('.with-collapse').click(function(){
		$(this).parents('.general-panel').find('.collapse-box').slideToggle(400);
		$(this).find('a').toggleClass('c-show')
	})
	
	/* delete notice re-usable codes */
	$(".notice .delete_notice").click(function(){
		$(this).parents(".notice").animate({ opacity: "hide" }, "slow");
	});
	
	
	/* navigation and menu */
	$('.account-link').toggle(
		function () {
			$(".my-menu").fadeIn();
			$(this).addClass('open');
		},
		function () {
			$(".my-menu").hide();
			$(this).removeClass('open');
		});
			
	$("#key_word, #group_keyword").focus(
	 	function() {
	  	// only select if the text has not changed
	  	if(this.value == this.defaultValue){
	   		this.value="";
				$(this).addClass('focused');
	  	}
	 })
	
	$('.browse_nav, .learn_nav').click(
		function () {
			$(this).toggleClass('show');
			$(this).siblings('li').removeClass('show')
		}
	)
	
	
	$('.prohibited-link').click(function() {
		$("<div id='prohibited_container' class='prohibited_container' style='display:none'></div>").load('/seller/prohibited #prohibited', function(){
			$('#prohibited_container').slideDown('slow');
			$('#lb_content').removeClass('spinner')
		}).lightbox();
		return false;
	})
	
	$('.f-page a, .slider-link a, .e-signup, .t-pagination a, .dropdown ul .active, .user-account .search-sort a').not('.transactions .search-sort a').mouseup(function(){
		$(this).removeClass('mousedown')
	}).mousedown(function(){
		$(this).addClass('mousedown')
	})
	
	$('.search-sort a, .more-gallery, .tags a, .navigation a, .rp-links a').not('.view-type a').mousedown(function(){
		$(this).addClass('mousedown');
		$('.search-sort .active').removeClass('active');
	})
	
	$('.view-type a, .user-account .search-sort a').mousedown(function(){
		$('.view-type a').removeClass('mousedown');
		$(this).addClass('mousedown');
	})
	
	$('.categories li a, .mcategories li a').mousedown(function(){
		$(this).addClass('mousedown');
		$('.categories .active').removeClass('active');
	})
	
	/* Submenu re-usable codes */
	$('.menu-text a.active').not('.search_results .menu-text a.active').toggle(
		function(){
		$('.menu-text').addClass('show');
	},
		function() {
		$('.menu-text').removeClass('show');
	});
		
	/* theme feeback */
	$('.theme-feedback').click(function(){
		$("<div id='popup_container' class='popup_container' style='display:none'></div>").load('/community/theme-feedback #theme-feedback', function(){
			$('#popup_container').slideDown('slow');
			$('#lb_content').removeClass('spinner');
		}).lightbox({'width': 648});
		return false;
	})
	
	/* Ubiquitous favorite action */

		
	/* Countries we ship to */
	$('.countries-link').click(function(){
		$("<div id='popup_container' class='popup_container' style='display:none'></div>").load('/product/ajax-countries .countries-block', function(){
			$('#popup_container').slideDown('slow');
			$('#lb_content').removeClass('spinner');
		}).lightbox({'width': 648});
		return false;
	})
	
	/* How safe to buy */
	$('.buy-safety-link').click(function(){
		$("<div id='popup_container' class='popup_container' style='display:none'></div>").load('/buy/how-safe-to-buy .buy-safety-block', function(){
			$('#popup_container').slideDown('slow');
			$('#lb_content').removeClass('spinner');
		}).lightbox({'width': 930});
		return false;
	})
	
	/* IE focus bug fix  */
	if ($.browser.msie){

		$('input, textarea').focus(function(){
			$(this).addClass('focus');
		});

		$('input, textarea').blur(function(){
			$(this).removeClass('focus');
		})
	}
	
		/* notification */
	$('.notification-link .inner-nl').toggle(function () {
			$(".notification-link ul").fadeIn();
			$(this).addClass('open');
		},
		function () {
			$(".notification-link ul").hide();
			$(this).removeClass('open');
		});
		
})
$.active = 1;
$.notice = function(type, message) {
	//types of notices are notice, error, success
	//var fs_notice = "<div id='fs-notice' class='fs-notice' style='display:none'><span class='close-notice'><a href='#'>X</a></span><div class='fs-content'></div></div>";
	//$('body').append(fs_notice);
	$('.fs-notice').removeClass('type-error');
	$('.fs-notice').addClass('type-'+type);
	$('.fs-content').html(message);
	$('.fs-notice').slideDown();
	var timer = setTimeout ( "$('.fs-notice').slideUp(); clearTimeout ("+timer+");", 10000 );
}

$().ready(function() {

	/* #2 Step - Upload_Organizer - Slide Function */
	$("a.slide_button").toggle(
		
		function () {
		$('div.slide-box_' + $(this).css('id')).animate( { left:"-225px" }, { queue:false, duration:500 } )
      },
      function () {
		$('div.slide-box_' + $(this).css('id')).animate( { left:"0" }, { queue:false, duration:500 } );
      }
    );

	/* Seller Account - #2 Upload - Organizer */
	$(".notice .delete_notice").click(function(){
	  $(this).parents(".notice").animate({ opacity: "hide" }, "slow");
	});   

	/* Seller Account - Transactions > Rating */
	$('.rating_area').css({display: "none"});

	$("a.rating_button").click(function() {
		$(this).parent().parent().next('.rating_area').toggle();
		$(this).toggleClass("active");
	});	

	/* Seller Account Page - Archive Photo */
	$("a.edit-picture").css({opacity:"0", position: "absolute", zIndex: "5000", height: "70px"});
	$("div.archive-box").hover(
		function () {
			$("a.edit-picture", this).animate( { opacity:"0.8" }, { queue:false, duration:200 } )
		},
		function () {
			$("a.edit-picture", this).animate( {opacity:"0" }, { queue:false, duration:200 } );
		}
	);

	/* Seller Account Page - Messages */
    
    $('.messages ul li .column_four').css({display: "none"});
    
    $(".message_title a").click(function() {
		$(this).parent().next().next().next('ul li .column_four').toggle();
		$(this).toggleClass("active");
	});
	
/* Seller Account - Information */

	$('.cover a.button').click(function(){ 
        $(this).parents(".cover").animate({ opacity: "hide" }, "slow"); 

        if($(this).parents(".cover").is(':hidden')){ 
                $(this).parents(".cover").animate({ opacity: "show" }, "slow");
        } 
        else{ 
                $(this).parents(".cover").animate({ opacity: "hide" }, "slow");
        }
        return false;
	});
	
$(".cover a.button").click(function(){
	
	if( $(element).is(":visible") == "true" ){
   	$(this).parents(".cover").hide();
	}
	else{
 	$(this).parents(".cover").show();
	}
	return false;
	});	
	
});

// Lightbox

(function($){
  
  $.closeLightbox = function() {
			$('#lb_shadow').hide();
			$('#lb_main').hide();
			
			$('body').css('overflow', 'auto');
			$('#lb_content').addClass('spinner');
  };
	
	$.fn.lightbox = function(options){
		
		var defaults = {width: "560px",height: "auto"};
		 
		var options = $.extend(defaults, options);
		
		return $(this).each(function(){
			obj = $(this);
			$('#lb_content').html(obj);
			$('#lb_content').addClass('spinner');
			$('#lb_shadow').show();
			
			left_offset = "-" + parseInt(options.width)/2 + "px"
			
			$('#lb_main').fadeIn(500)
									 .css("width", options.width)
									 .css("height", options.height)
									 .css("margin-left", left_offset);
			
			
			$('body').css('overflow', 'hidden');
			
			$('.lb_close, .lb_cancel').click(function(){
			  $.closeLightbox();
			});
			
		})
	};
	
  $.fn.toRelativeTime = function() {
    this.each(function() {
      var $this = $(this);
      $this.text(Date.fromString($this.html()).toRelativeTime());
    });
  };
	
})(jQuery)

$.createMainLightbox = function(){
	var lightbox_shadow = "<div id='lb_shadow' class='lb_shadow' style='display:none'></div>"
	var main_lightbox = "<div id='lb_main' class='lb_main' style='display:none'>" +
												"<div id='lb_cs' class='lb_cs'>" +
													"<div id='lb_cb' class='lb_cb'>" +
														"<div id='lb_title' class='lb_title'>" +
															"<div class='lb_close'></div>" +
														"</div>" + 
														"<div id='lb_content' class='lb_content'></div" +
													"</div>" +
												"</div>" +  
											"</div>";
											
	$('body').append(lightbox_shadow).append(main_lightbox);
}
$.createMainLightbox();

/**
 * Quickly fetch or retrieve user settings.
 */
$.userSettings = function(fn_or_settings, fn, options) {
  var settings = null;
  if(fn) {
    settings = fn_or_settings;
  } else {
    fn = fn_or_settings;
  }
  if(settings) {
    $.get("/user-settings/set", {'fields': settings}, function(response) {
      fn(response.user, response.settings);
    }, 'json');
  } else {
    $.get("/user-settings/get", function(response) {
      fn(response.user, response.settings);
    }, 'json');
  }
};


// Beta counter

var current="Beta"
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

function countdown(yr,m,d){
theyear=yr;themonth=m;theday=d
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[m-1]+" "+d+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring) 
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if(dday==0&&dhour==0&&dmin==0&&dsec==1){
//document.forms.count.count2.value=current
$('.counter').html(current);
return
}
else
//document.forms.count.count2.value=Math.abs((dday))+ "d, "+Math.abs(dhour)+"h, "+Math.abs(dmin)+"min, and "+Math.abs(dsec)+"sec"
$('.counter').html(Math.abs((dday))+ "d "+Math.abs(dhour)+"h "+Math.abs(dmin)+"m "+Math.abs(dsec)+"s");
setTimeout("countdown(theyear,themonth,theday)",1000)
}
//enter the count down date using the format year/month/day

// Convert Currency

function currencyConverter(){

	cur = $('.currency:first');
	from = cur.attr('from');
	to = cur.attr('to');

	if(to == from) {
		to = 'USD';
	}
	if (to != from){
		$.ajax({
			type: "POST",
			url: "/ajax/convert-currency",
			data: {from: from, to: to},
			success: function(data){
				$('.currency').each(function() {
					fromprice = removeCommas($(this).children('span.price').text());
					toprice = Number(Math.floor(data.buffer * fromprice));
					toprice = addCommas(toprice);
					cent = '';
					if(toprice != 0) {
						if(to == 'USD'){
							cent = '<span class="cent-dec">.00</span>';
						}
						tag = ' <span class="approx"><span class="code">'+data.tosymbol+'</span><span class="price">' + toprice + cent + '</span></span>';
						//$(this).append(tag);
						//if($(this).parents('div').children('.approx').length == 0) {
							$(tag).insertBefore($(this));	
							$('.currency').removeClass('currency');
							$('.price-loader').hide();
							$('.switch-btn').show();
						//};
					} else {
						$('.code, .price').show();
						$('.price-loader').hide();
						return false;
					}

				});
			},
			dataType: "json"
		});
	}
}

function showPreview() {
	$('.item-list .preview-link').click(function(){

		$(this).parents('.img-c').addClass('loading');

		var item_id = $(this).parents('li').attr('id').match((/\d+/g))[0];
		var item = $(this).parents('li');
		item.addClass('active-preview');

		if(item.children('.preview').length != 0){
			$('.img-c').removeClass('loading');
			item.children('.preview').fadeIn(300);
			item.mouseleave(function(){
				item.children('.preview').fadeOut(200);
				item.removeClass('active-preview');
			})
		} else {
			item.append('<div style="display:none" class="preview" id="previewid_' + item_id + '"></div>');
			item.children('.preview').load('/product/ajax-item-preview .item-preview', {'pid' : item_id, dataType: "json"}, function(){
				item.children('.preview').fadeIn(300);
				currencyConverter();
				$('#itemid_' + item_id + ' .fave-link').click(function() {

					$.post('/product/ajax-favorite-this',{pid:item_id},function(data) {
						if (data.result == '1') {
							item.find('.favex').addClass('favorited');
							item.find('.favex').find('.info-text').html('You like this');
							item.find('.fave-count').html(data.message);
						}
						else {
							if(data.message == 'trigger-login') {
      			    fsNeedLogin();
      			  } else {
      			    $.notice('error', data.message);
      			  }
						}
						return false;
					},
					"json");
				});

				$('#itemid_' + item_id + ' .favex').hover(function(){
					$(this).find('.information').fadeIn();
				},function(){
						$(this).find('.information').hide();
				})
				
				$('.img-c').removeClass('loading');
				item.mouseleave(function(){
					item.children('.preview').fadeOut(200);
					$(this).removeClass('active-preview');
				})
			});
		}
	})
};

function showBuyerCountry(){
	var item = $('.purchases-list li');
	item.each(function(){
		var item_id = $(this).attr('id').match((/\d+/g))[0];
		var count = $(this).find('.recent-purchases').attr('id').match((/\d+/g))[0];
		var container = $(this).find('.country-list');
		
		container.load('/people/ajax-show-countries .country-list',{pid:item_id, count:count}, function(data){
			
		})
	
	})
}

function faveLink() {	
	var item = $('.item-list li');
	item.each(function(){
		var item_id = $(this).attr('id').match((/\d+/g))[0];
		$(this).find('.fave-link').click(function() {
			var item = $(this).parents('li');
			$.post('/product/ajax-favorite-this',{pid:item_id},function(data) {
				if (data.result == '1') {
					item.find('.favex').addClass('favorited');
					item.find('.favex').find('.info-text').html('You like this');
					item.find('.fave-count').html(data.message);
				}
				else {
					if(data.message == 'trigger-login') {
				    fsNeedLogin();
				  } else {
				    $.notice('error', data.message);
				  }
				}
				return false;
			},
			"json");
		});
		
		$('#itemid_' + item_id + ' .favex').hover(function(){
			$('.information').hide();
			$(this).find('.information').fadeIn();
		},function(){
				$(this).find('.information').hide();
				$('.information').hide();	
		})
		
	})
	
}

function showGroupActivities() {

	$('.groups-block li').each(function(){
		var item_id = $(this).attr('id').match((/\d+/g))[0];
		//var user_id = $(this).find('.recent-comment').attr('id').match((/\d+/g))[0];
		//var user_id = 2;
		$('<li class="activity-list" style="display:none"></li>').insertAfter(this).load('/group/ajax-recent-activity .activity-content', {'pid' : item_id, dataType: "json"}, function(){
			$(this).slideDown('fast');
			$('.relative_time').toRelativeTime();
		  $('.relative_time').removeClass('relative_time');
			
			if($('.comment textarea').val() == ''){
				$('.comment textarea').addClass('blank');
				$('.comment textarea').val('');		
			} else {
				$('.comment textarea').addClass('not-blank');
				$(this).parents('form').find('.submit-comment').show();
			}
			
			$(this).find('.comment textarea').focus(function(){
				$(this).parents('form').attr('id', 'new-comment-form').find('.submit-comment').show();
				$(this).parents('li').find('.group-comments').attr('id', 'group-comments');
				var comments = new Comments(null, 'group', item_id); 
				return false;
			});

			$(this).find('.comment textarea').blur(function(){
				if($(this).val() == ''){
					$(this).addClass('blank');
					$(this).removeClass('not-blank');
					$(this).parents('form').attr('id', '').find('.submit-comment').hide();
					$(this).parents('li').find('.group-comments').attr('id', '');
				} else {
					$(this).removeClass('blank');
					$(this).addClass('not-blank');
					$(this).attr('height', 'auto');
				}
			});

	    $('.activity-list textarea').autogrow({expandTolerance: 1});
			
		})
	})
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function removeCommas(nString)
{
	var rgx = /,/;
	nString = nString.replace(rgx, '');
	return nString
}

/* Nano Templates (Tomasz Mazur, Jacek Becela) */

(function($){
  $.nano = function(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
      var keys = key.split("."), value = data[keys.shift()];
      $.each(keys, function () { value = value[this]; });
      return (value === null || value === undefined) ? "" : value;
    });
  };
})(jQuery);

/*
* Returns a description of this past date in relative terms.
* Example: '3 years ago'
*/
Date.prototype.toRelativeTime = function() {
  var delta = new Date() - this;
  var units = null;
  var conversions = {
    millisecond: 1, // ms -> ms
    second: 1000, // ms -> sec
    minute: 60, // sec -> min
    hour: 60, // min -> hour
    day: 24, // hour -> day
    month: 30, // day -> month (roughly)
    year: 12 // month -> year
  };
 
  for(var key in conversions) {
    if(delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }
 
  // pluralize a unit when the difference is greater than 1.
  delta = Math.floor(delta);
  if(delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
};
 
/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};


