// init the page for js and set tabs
$(function(){
  $("body").removeClass('no-script');
  $('#tabs').tabs();
});

$(function(){
  var selection_description = $('#selections_show #content .description')
  selection_description.hide();
  
  // $('#selections_show #content .banner').click(function(){
  //   selection_description.slideToggle('slow');
  // });
  
  $('#selections_show #content .toggle').toggle(function() {
        $(this).children('.toggle-indicator').html('Hide Details');
        selection_description.slideToggle('slow');

    },function(){
        $(this).children('.toggle-indicator').html('Show Details');
        selection_description.slideToggle('slow');
  });
  $("#quick-cart").submit(function() {
	$.get($(this).attr("action"), {"id":  $(this).find("select[name=id]").val() }, function(data) {
		$.facebox(data);
	});
	return false;
  });
});





// $(document).ready(setupZoom);
function highlight_stars(n) {
  for(var i=1;i<=n;i++)
    $('#rate_this_' + i).find("img").attr('src', "/images/star_filled.gif");
  for(var i=n+1;i<=5;i++)
    $('#rate_this_' + i).find("img").attr('src', "/images/star_unfilled.gif");
}

function swap_product_image(el, fullsize_url, thumb_url, can_enlarge) {
	$('#hero_pic').attr('src', fullsize_url);
	$('.more_pics a').removeClass('selected');
	$(el).addClass('selected');
	if(can_enlarge) {
		$('.embiggen').slideDown(100);
		$('.embiggen').attr('href', thumb_url);
		$('.hero a').attr('rel', '');
		$('.hero a').attr('href', thumb_url);
		$('.hero a').removeClass('cant_zoom');
	} else {
		$('.embiggen').slideUp(100);
		$('.hero a').attr('rel', 'disable');
		$('.hero a').addClass('cant_zoom');
	}
	el.blur();
}

function show_panel(id, scope) {
	$(scope + ' .tab_panel').hide();
	$(scope + ' .tab').removeClass('selected');
	$(scope + ' #' + id + '_tab').addClass('selected');
	$(scope + ' #' + id).show();
	document.location.hash = '#' + id + '_panel';	
}

function update_shipping_elements(options, selected_option, subtotal, total, gift_total, remaining) {
	// shipping line
	options.hide();
	selected_option.show();

	// total calc
	var subtotal_amount = parseFloat(subtotal.html().replace(/[^0-9\.]/g,''));
	var cost = parseFloat(selected_option.html().replace(/[^0-9\.]/g,''));
	var total_amount = subtotal_amount + cost;

    if (gift_total != undefined && gift_total.length > 0) {
        var gift_total_amount = parseFloat(gift_total.html().replace(/[^0-9\.]/g, ''));
        var remaining_amount = total_amount - gift_total_amount;

        if (remaining_amount < 0) {
            remaining_amount = 0;
        }

        remaining.html('$' + remaining_amount.toFixed(2) + ' USD');
    }

	total.html('$' + total_amount.toFixed(2) + ' USD');
}

function update_shipping_cost(country) {
    update_shipping_elements(
        $('#shipping_cost span'),
        $('#shipping_cost #shipping_' + country),
        $('#subtotal'),
        $('#total, #top_total')
    );
}

// for checkout.
$(document).ready(function() {
    $("#same_address").change(function() { 
			if (this.checked) { 
				$("#shipping").slideUp(400); 
			} else {
				$("#shipping").slideDown(400);
			}});
	if ($("#same_address").attr("checked")) {
		$("#shipping").hide(); 
	}
});

function cc_type(num) {
	num = $.trim(num);
	
	if(num[0] == '4')
		return 'visa';
		
	if(num.slice(0,4) == '6011' || num.slice(0,2) == '65')
		return 'discover';
		
	first_two = parseInt(num.slice(0,2));
	if(first_two >= 51 && first_two <= 55)
		return 'master';
	
	if(first_two == 34 || first_two == 37)
		return 'american_express'
		
	return null;
}



// For address forms
var PROVINCES = {
    'United States': [["Alabama", "AL"], ["Alaska", "AK"], ["American Samoa", "AS"], ["Arizona", "AZ"], ["Arkansas", "AR"], ["Armed Forces Americas", "AA"], ["Armed Forces Europe", "AE"], ["Armed Forces Pacific", "AP"], ["California", "CA"], ["Colorado", "CO"], ["Connecticut", "CT"], ["Delaware", "DE"], ["District of Columbia", "DC"], ["Federated States of Micronesia", "FM"], ["Florida", "FL"], ["Georgia", "GA"], ["Guam", "GU"], ["Hawaii", "HI"], ["Idaho", "ID"], ["Illinois", "IL"], ["Indiana", "IN"], ["Iowa", "IA"], ["Kansas", "KS"], ["Kentucky", "KY"], ["Louisiana", "LA"], ["Maine", "ME"], ["Marshall Islands", "MH"], ["Maryland", "MD"], ["Massachusetts", "MA"], ["Michigan", "MI"], ["Minnesota", "MN"], ["Mississippi", "MS"], ["Missouri", "MO"], ["Montana", "MT"], ["Nebraska", "NE"], ["Nevada", "NV"], ["New Hampshire", "NH"], ["New Jersey", "NJ"], ["New Mexico", "NM"], ["New York", "NY"], ["North Carolina", "NC"], ["North Dakota", "ND"], ["Northern Mariana Islands", "MP"], ["Ohio", "OH"], ["Oklahoma", "OK"], ["Oregon", "OR"], ["Palau", "PW"], ["Pennsylvania", "PA"], ["Puerto Rico", "PR"], ["Rhode Island", "RI"], ["South Carolina", "SC"], ["South Dakota", "SD"], ["Tennessee", "TN"], ["Texas", "TX"], ["U.S. Virgin Islands", "VI"], ["Utah", "UT"], ["Vermont", "VT"], ["Virginia", "VA"], ["Washington", "WA"], ["West Virginia", "WV"], ["Wisconsin", "WI"], ["Wyoming", "WY"]],
		'Canada': [['Ontario', 'ON'], ['Quebec', 'QC'], ['British Columbia', 'BC'], ['Alberta', 'AB'],
		        	['Manitoba', 'MB'], ['Saskatchewan', 'SK'], ['Nova Scotia', 'NS'], ['New Brunswick', 'NB'],
		        	['Newfoundland and Labrador', 'NL'], ['Prince Edward Island', 'PE'], ['Northwest Territories', 'NT'],
			        ['Yukon', 'YK'], ['Nunavut', 'NU']],
    'Belgium': ['Antwerp', 'East Flanders', 'Flemish Brabant', 'Limburg', 'West Flanders', 'Hainaut', 'Liège',
        'Luxembourg', 'Namur', 'Walloon Brabant'],
    'Denmark': ['Hovedstaden', 'Midtjylland', 'Nordjylland', 'Sjælland', 'Syddanmark'],
    'Finland': ['Åland', 'Eastern Finland', 'Lapland', 'Oulu', 'Southern Finland', 'Western Finland'],
    'Germany': ['Baden-Württemberg', 'Bavaria', 'Berlin', 'Brandenburg', 'Bremen', 'Hamburg', 'Hesse',
        'Mecklenburg-Vorpommern', 'Lower Saxony', 'North Rhine-Westphalia', 'Rhineland-Palatinate', 'Saarland',
        'Saxony', 'Saxony-Anhalt', 'Schleswig-Holstein', 'Thuringia'],
    'Greece': ['Attica', 'Central Greece', 'Central Macedonia', 'Crete', 'East Macedonia and Thrace',
        'Epirus', 'Ionan Islands', 'North Aegean', 'Peloponnese', 'South Aegean', 'Thessaly', 'West Greece',
        'West Macedonia', 'Mount Athos'],
    'Ireland': ['Leinster', 'Munster', 'Connacht', 'Ulster'],
    'Israel': ['Jerusalem District', 'North District', 'Haifa District', 'Center District',
        'Tel Aviv District', 'South District', 'Judea and Samaria Area'],
    'Italy': ['Abruzzo', 'Aosta Valley', 'Apulia', 'Basilicata', 'Calabria', 'Campania', 'Emilia-Romagna',
        'Friuli-Venezia', 'Lazia', 'Liguria', 'Lombardy', 'Marche', 'Molise', 'Piedmont', 'Sardinia', 'Sicily',
        'Trentino-Alta Adige/Südtirol', 'Tuscany', 'Umbria', 'Veneto'],
    'Mexico': ['Federal District (Mexico City)', 'Aguascalientes', 'Baja California', 'Baja California Sur',
        'Campeche', 'Chiapas', 'Chihuahua', 'Coahuila', 'Colima', 'Durango', 'Guanajuato', 'Guerrero', 'Hidalgo',
        'Jalisco', 'Mexico State', 'Michoacán', 'Morelos', 'Nayarit', 'Nuevo León', 'Oaxaca', 'Puebla', 'Querétaro',
        'Quintana Roo', 'San Luis Potosí', 'Sinaloa', 'Sonora', 'Tabasco', 'Tamaulipas', 'Tlaxcala', 'Veracruz',
        'Yucatán', 'Zacatecas'],
    'Norway': ['Akershus', 'Aust-Agder', 'Buskerud', 'Finnmark', 'Hedmark', 'Hordaland', 'Møre og Romsdal',
        'Nordland', 'Nord-Trøndelag', 'Oppland', 'Oslo', 'Østfold', 'Rogaland', 'Sogn og Fjordane', 'Sør-Trøndelag',
        'Telemark', 'Troms', 'Vest-Agder', 'Vestfold'],
    'Sweden': ['Stockholm', 'Västerbotten', 'Norrbotten', 'Uppsala', 'Södermanland', 'Östergötland',
        'Jönköping', 'Kronoberg', 'Kalmar', 'Gotland', 'Blekinge', 'Skåne', 'Halland', 'Västra Götaland',
        'Värmland', 'Örebro', 'Västmanland', 'Dalarna', 'Gävleborg', 'Västernorrland', 'Jämtland'],
    'Switzerland': ['Aargau', 'Appenzell Innerrhoden', 'Appenzell Ausserrhoden', 'Basel-Stadt',
        'Basel-Landschaft', 'Bern', 'Fribourg', 'Genève', 'Glarus', 'Graubünden', 'Jura', 'Lucerne', 'Neuchâtel',
        'Nidwalden', 'Obwalden', 'Schaffhausen', 'Schwyz', 'Solothurn', 'St. Gallen', 'Thurgau', 'Ticino', 'Uri',
        'Valais', 'Vaud', 'Zug', 'Zürich'],
    'United Kingdom': ['England', 'Northern Ireland', 'Scotland', 'Wales']
};

var CountDownTimer = {
    init: function() {
        this.end_sec = $("span:first-child",this).hide().html()
    },
    update: function(e) {
        // use utc times?
        // getUTCHours, etc.
        var secs = this.end_sec - Math.floor((new Date()).getTime()/1000);
        if (secs < 0) {
            $(this).stopTime().hide();
            return;
        }
        $(".days",this).text(this.digits(Math.floor(secs/86400)));
        $(".hours",this).text(this.digits(Math.floor(secs/3600)%24));
        $(".minutes",this).text(this.digits(Math.floor(secs/60)%60));
        $(".seconds",this).text(this.digits(secs%60));
    },

    digits: function(n) {
        return n.toString();
    },

    start: function() {
        this.update();
        $(this).everyTime(1000,function(){ this.update()});
    }
};

$(document).ready(function() {
        // set all the coupon fields to the same when one is changed.
        $("#cart_wrapper form").bind("submit",function(e) {
                var code = $("#add_coupon .coupon_code_input").val();
                $("#cart_wrapper .coupon_code_input").val(code);
            });

		$('.global-flash').each(function() {
			$(this).append('<a href="#" class="close-flash" style="position:absolute;display:block;right:10px;top:0.6em"><image src="/images/close.gif" /></a>');
		});
		$(".close-flash").live("click", function() {
			$(this).closest('.global-flash').slideToggle();
		});
		
		$(".search-box").focus(function() {	
			if ($(this).attr("placeholder") == $(this).val()) {
				$(this).val("");
				$(this).css({"color":"black"});
			}
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val($(this).attr("placeholder"));
				$(this).css({"color":"#aaa"});
			} else if ($(this).val() == $(this).attr("placeholder")) {
				$(this).css({"color":"#aaa"});
			}
		}).each(function() {
			if ($(this).attr("placeholder")  == $(this).val()) {
				$(this).css({"color":"#aaa"});
			} 
		});
		
		if (RegExp(" AppleWebKit/").test(navigator.userAgent)) {
			box = $("#header .search-box").hide();
			box.replaceWith($('<input type="search" name="q" autosave="perfume" results="0" placeholder="Search" class="pretty-search" size="30" />'));
		}
});

function increment_cart_count() {
	var arr = $(".cart_status a").html().match(/([0-9]+) items?/);
	count = parseInt(arr[1]) + 1;
	str = count + " " + (count == 1 ? "item" : "items");
	$(".cart_status a").html($(".cart_status a").html().replace(/[0-9]+ items?/, str));
}