$().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");
	});
	
	/* resusable code for tips */
	$(".with-htip").hover(
		function(){
			var tip = $(this).children('.htip');
			var pointer = tip.children('.tipimg').length != 0 ? '' : '<img class="tipimg" src="http://static.flutterscape.net/images/nav-pointer.png" />';
			$(this).css({'position' : 'relative'});
			tip.append(pointer).fadeIn('fast');
		},
		function(){
			$(this).children('.htip').hide();
		})
	
	
	/* navigation and menu */
	$('.account-link').toggle(
		function () {
			$(".my-menu").fadeIn();
			$(this).addClass('open');
		},
		function () {
			$(".my-menu").hide();
			$(this).removeClass('open');
		});
			
	$("#group_keyword").focus(
	 	function() {
	  	// only select if the text has not changed
	  	if(this.value == this.defaultValue){
				$(this).addClass('focused');
	  	}
	 })
	
	$('.learn_nav').click(
		function () {
			$(this).toggleClass('show');
			$(this).siblings('li').removeClass('show')
		}
	)
	
	// Form focus control
	$('.with-inline-label p input').each(function(){
		if($(this).val() == ''){
			$(this).addClass('blank');
			$(this).val('');		
		}
	})
	
	if($('.with-inline-label p textarea').text() == ''){
		$('.with-inline-label p textarea').addClass('blank');
		$('.with-inline-label p textarea').val('');		
	}
	
	$('.with-inline-label p input, .with-inline-label p textarea').blur(function(){
		if($(this).val() == ''){
			$(this).addClass('blank');
			$(this).removeClass('not-blank');
		} else {
			$(this).removeClass('blank');
			$(this).addClass('not-blank');
		}
		
	});
	
	$('.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;
	})
		
	/* 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+");", 4000 );
}

$().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');
			$('.main').removeClass('overlayed');
  };
	
	$.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');
			$('.main').addClass('overlayed');
			
			$('.lb_close, .lb_cancel').click(function(){
			  $.closeLightbox();
			});
			
		})
	};
	
  $.fn.toRelativeTime = function() {
    this.each(function() {
      var $this = $(this);
			if(!$this.hasClass('relative_on')){
	      $this.text(Date.fromString($this.html()).toRelativeTime());
				$this.show();
				$this.addClass('relative_on');
			}
    });
  };
	
})(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>";
											
$().ready(function(){											
	$('.main').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

var currency_rate = '';

function currencyConverter(){

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

	if(to == from) {
		if(to == 'JPY') {
			$('.currency').show();
			$('.loading').hide();
			currency_rate = 1;
			return false;
		}
		to = 'USD';
	}

	//delete conversion cookies if user change currency information
	if($.cookie('tocurrency')) {
		if($.cookie('tocurrency') != to || $.cookie("conversion") == 0.00) {
			$.cookie("tosymbol", null, {expires : 7, path : '/'});
			$.cookie("conversion", null, {expires : 7, path : '/'});
			$.cookie("tocurrency", null, {expires : 7, path : '/'});
		}
	}

	if (to != from){
		
		//check for existing cookies
		if($.cookie('tocurrency')) {
			var conversion = $.cookie('conversion');
			currency_rate = conversion; 
			var tosymbol = $.cookie('tosymbol');
			convertDOM(conversion, tosymbol);
		} else {

			$.ajax({
				type: "POST",
				url: "/ajax/convert-currency",
				data: {from: from, to: to},
				success: function(data){
					//set cookies

					$.cookie("tosymbol", data.tosymbol, {expires : 7, path : '/'});
					$.cookie("conversion", data.buffer, {expires : 7, path : '/'});
					$.cookie("tocurrency", to, {expires : 7, path : '/'});	
					currency_rate = data.buffer;
					convertDOM(data.buffer, data.tosymbol);
				},
				dataType: "json"
			});
		}
	}
	
	function convertDOM(conversion, tosymbol){
		$('.currency').each(function() {
			var fromprice = removeCommas($(this).children('span.price').text());
			var toprice = Number(Math.floor(conversion * fromprice));
			var toprice = addCommas(toprice);
			var cent = '';
			var to_lcode = '';

			if(toprice != 0) {
				if(to == 'USD'){
					cent = '.00';
					to_lcode = 'US';
				}

				tag = ' <span class="approx"><span class="code">' + to_lcode + tosymbol+ '</span><span class="price">' + toprice + cent + '</span></span>';

					$(tag).insertBefore($(this));	
					$('.currency').removeClass('currency');
					$('.price-loader').hide();
					$('.switch-btn').show();

			} else {
				$('.code, .price').show();
				$('.price-loader').hide();
				return false;
			}
		});
	}
	
}

function showPreview() {
	$('.item-list .preview-link').click(function(){
		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) {
		item.children('.preview').fadeIn(300);
		item.mouseleave(function(){
			item.children('.preview').fadeOut(200);
			item.removeClass('active-preview');
		})
	} else {
		  $(this).addClass('loading');
		   var link = $(this);
			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(500);
				setTimeout(function(){link.removeClass('loading');}, 1000)
				
				item.mouseleave(function(){
					item.children('.preview').fadeOut(200);
					$(this).removeClass('active-preview');
				})
				
			});
		}
	})
};

function showBuyerCountry(){
	var item = $('.purchases 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 items = $('.item-list li').not('.list-spacer');
	items.each(function(){
		if($(this).attr('id')) {
		var item_id = $(this).attr('id');
		item_id = item_id.match((/\d+/g))[0];
		$(this).find('.want_this').unbind('click');
		$(this).find('.want_this').click(function() {
			var item = $(this).parents('li');
			$.post('/product/ajax-favorite-this',{pid:item_id},function(data) {
				if (data.result == '1') {
					item.find('.want_this').addClass('wanted');
					item.find('.wanted').find('.info-text').html('You like this');
					item.find('.want_count').hide().fadeIn(400).addClass('added').html(data.message);
					// finally record this in GA
					_gaq.push(['_trackEvent', 'Product', 'Want', 'id', item_id, true]); // last param=true=do not include this in bounce rate
				}
				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();	
		})
		
	})
	
}*/

//otimized FaveLink
function faveThis(id) {	
	var item_id = id;
	var itemsel = '#itemid_' + item_id;
	if(!$(itemsel).length) {
		var itemsel = '.itemid_' + item_id;
	}

	$(itemsel).find('.want_this img').hide();
	$(itemsel).find('.want_this').append('<span class="loading" style="display:block; position: relative; top: 18px"></span');
	var item = $(itemsel);
			$.post('/product/ajax-favorite-this',{pid:item_id},function(data) {
				if (data.result == 1 || data.result == -1) {
					
					//item.find('.wanted').find('.info-text').html('You like this');
					item.find('.want_count').hide().addClass('added').fadeIn(400).html(data.message)
					// finally record this in GA
					if (data.result == '1') {
						item.find('.want_this').addClass('wanted');
						_gaq.push(['_trackEvent', 'Product', 'Want', item_id+'#'+$('#itemid_'+item_id).attr('title'), 1, true]); // last param=true=do not include this in bounce rate
					} else {
						item.find('.want_this').removeClass('wanted');
						_gaq.push(['_trackEvent', 'Product', 'Unwant', item_id+'#'+$('#itemid_'+item_id).attr('title'), 1, true]); // last param=true=do not include this in bounce rate
					// change tooltip accordingly
					}
					item.find('a.want_this').attr('title', data.result == 1? 'Remove from Wants list': 'Add to Wants list');
					$(item).find('.want_this img').show();
					$(item).find('.loading').remove();
				}
				else {
					if(data.message == 'trigger-login') {
						fsNeedLogin();
					} else {
						$.notice('error', data.message);
					}
				}
				return false;
			},
			"json");
}

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 = /,/g;
	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(" ");
	} else if(delta >= 1) {
		return [delta, units, "ago"].join(" ");
	} else {
		return "moments ago";
	}

};
 
/*
* 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));
};


