
/* These are code from fns.js => pageLoaded() to fix up the popup, it is moved to here so that it can be called via onclick so that it works with AJAX.
Also copied some other necessary lines from pageLoaded() here to fix up popup, reason why we are not re-using fns.js => pageLoaded() because
it will run itself on the landing page again creating unwanted side-effects.  */
function popup_tweaks() {
	$('#frame-labels .radio[name=frame]').each( function() {
		if ($(this).is(':checked')) {
			$(this).parents('label:eq(0)').addClass('checkedlabel');
		}
	});
	$('#frame-labels .radio[name=frame]').change( function() {
		$('#frame-labels label').removeClass('checkedlabel');

		if ($(this).is(':checked')) {
			$(this).parents('label:eq(0)').addClass('checkedlabel');
		}
		
		Cufon.refresh();
	});
	$('#frame-labels .sku').each( function() {
		if ($(this).is(':checked')) {
			$(this).parents('label:eq(0)').addClass('checkedlabel');
		}
	});
	$('#frame-labels .sku').change( function() {
		$('#frame-labels label').removeClass('checkedlabel');

		if ($(this).is(':checked')) {
			$(this).parents('label:eq(0)').addClass('checkedlabel');
		}
		
		Cufon.refresh();
	});
	$('.topnav > li > a, .productsnav > ul > li > a, .main-btn, .sub-btn, .grey-btn, .mid-btn').each(
		function() {
			if ($(this).find('span').length) {
				return;
			}
			
			var text = $(this).html();
			$(this).html('').append('<span></span>').find('span')
					.html(text);
		}
	);
	$('.smlink').each(
		function() {
			if ($(this).parent().is('p') || $(this).hasClass('nojs')) {
				return;
			} else {
				$(this).wrap('<p></p>').removeClass('smlink').parent().addClass('smlink');
			}
		}
	);
	$('ul.fix-last, .subnav > ul').each( function() {
		$(this).find('li:last-child').addClass('last');
	});
	$('.topnav li').each( function() {
		if ($(this).find('.dropdown').length) {
			$(this).addClass('has-dropdown');
		}
	});
	$('div[class*=col-]').each(
		function() {
			var number = parseInt($(this).attr('class').replace(
					/.*col-([\d]+).*/, '$1'));
			
			if (number < 20) {
				return;
			}
			
			$(this).addClass('width-col').css('width', number);
		}
	);

	Cufon.replace('.black');

	$('.carousel').jcarousel();

	/* Added by ACDC - adding close trigger to cancel button */
	$('#facebox .mid-btn-grey').live('click', function() {
		$(document).trigger('close.facebox');
		return false;
	});

	/* Added by ACDC - adding listeners for frame and matte selection */
	$('#facebox .frame_selector').live(
			'click',
			function() {
				select_frame($(this).html(), $(this).attr('price'), $(this)
						.attr('sku_id'), $(this).attr('frame_img'));
				return false;
			});
	$('#facebox .matte_selector').live(
			'click',
			function() {
				select_matte($(this).html(), $(this).attr('price'), $(this)
						.attr('sku_id'), $(this).attr('matte_img'));
				return false;
			});

	$('#facebox .add_frame_and_matte_cart').live('click', function() {
		add_frame_and_matte_cart();
		return false;
	});
	
	/* Added by ACDC - adding listeners for quick view adding */
	$('#facebox .add_quick_view_cart').live('click', function(){
		add_quick_view_cart();
		return false;
	});
}

// we need to cookie the user with their state based on their IP
var steiner_cookied_state = $.cookie('ip_state');

if (steiner_cookied_state == null || steiner_cookied_state == '') {
	$.ajax({
		url: '/getstate.php',
		data: {
			'randid' : Math.random()
		},
		success: function(data) {
			$.cookie('ip_state', data, { expires: 7 });
			steiner_cookied_state = data;
		}
	});
}

// if states is null or empty or steiner_cookied_state is null or empty return true.
// otherwise, return true if steiner_cookied_state is in
// "states".
// e.g., "NY|CA|FL|"
function can_show_targeted_box(states) {
	if (states == null || states == '' || steiner_cookied_state == null || steiner_cookied_state == '') {
		return true;
	} else {
		return states.indexOf(steiner_cookied_state) >= 0;
	}
}

function ajax_post_form(url, formId) {
	$.ajax({
		type: "POST",
		url: url,
		data: getFormValues($('#' + formId)[0]),
		success: function (response) {
			if (response.indexOf('success') >= 0) {
				location.reload(true);
				// $(document).trigger('close.facebox');
			} else {
				$.facebox(response);
				popup_tweaks();
			}
		}
	});
}

function ajax_facebox(url) {
	$.ajax({
		type: 'GET',
		url: url,
		success: function (response) {
			$.facebox(response);
			popup_tweaks();
		}
	});
}

function jsonp_show_form_facebox(jsonp_url, jst_id) {
	$.ajax({
		url: jsonp_url,
		data: { 'randid' : Math.random() },
		dataType: 'json',
		success: function(data) {
			var output = $('#' + jst_id).tmpl(data);
			$.facebox(output);
			popup_tweaks();
		}
	});
}

function jsonp_submit_form_facebox(jsonp_url, form_id, jst_id) {
	$.ajax({
		url: jsonp_url,
		data: getFormValues($('#' + form_id)[0]),
		dataType: 'json',
		success: function(data) {
			if (data.successfully_submitted) {
				location.reload(true);
			} else {
				var output = $('#' + jst_id).tmpl(data);
				$.facebox(output);
				popup_tweaks();
			}
		}
	});
}

// we need to cookie the user to only show the site takeover popup only once per session
var steiner_cookied_show_site_takeover = $.cookie('show_site_takeover');

function show_site_takeover() {
	if (steiner_cookied_show_site_takeover == 'no') {
		return;
	}

	$.cookie('show_site_takeover', 'no', { expires: 7 });
	
	if (site_takeover_json[0].link != null && site_takeover_json[0].link != '') {
		jQuery.facebox('<a href="#" class="close" style="margin-bottom:3px;">close</a>'+
						'<a href="' + site_takeover_json[0].link + '"><img src="' + site_takeover_json[0].image_src + '"></a>');
	}
}

function render_jcarousel(element) {
	element.jcarousel({
		vertical : false,
		scroll : 1,
		wrap : 'both',
		"buttonNextHTML" : null,
		"buttonPrevHTML" : null,
		initCallback : horizental_slider_callback
	});

	function horizental_slider_callback(carousel) {
		carousel.container.find('.carousel-btns a').live('click', function() {
			if ($(this).hasClass('btn-prev')) {
				carousel.prev();
				return false;
			} else {
				carousel.next();
				return false;
			};
		});
	}
}

$(function() {
	$("body").delegate('.quicksearch', 'change',  function() {
		if ($(this).val() != '') {
			$(location).attr("href", $(this).val());
		}
	});
});

function submit_popup_form(page, form_id) {
	$.post(page, get_form_values(form_id), function(data, textStatus, xhr) {
		if ((xhr.getResponseHeader('ACDC_ERROR') == 't') || (data.match('ACDC_ERROR'))) {
			$.facebox(data);
		} else {
			location.reload(true);
		}
	});
}

/* On success this method keeps the facebox open and does a template merge with the success data */
function jsonp_submit_form_keep_facebox(jsonp_url, form_id, jst_id, success_jst_id) {
	$.ajax({
		url: jsonp_url,
		data: getFormValues($('#' + form_id)[0]),
		dataType: 'json',
		success: function(data) {
			var output;
			
			if (data.successfully_submitted) {
				output = $('#' + success_jst_id).tmpl(data);
			} else {
				output = $('#' + jst_id).tmpl(data);
			}
			
			$.facebox(output);
			popup_tweaks();
		}
	});
}

/* This function is used by the solr_search plugin to "massage" any data for each result set item before it is
passed down to the jst template for display */
function solr_data_transform(item){
	var site_ref_code = item['site_ref_code'];
	var site_domain = pageVar[site_ref_code + '_DOMAIN'];
	item['site_domain'] = site_domain;
	
	if($.cookie("isWholesale") == "true"){
		item['price'] = format_price(item['wholesale_price']);
	}else if(item['list_price'] != null){
		var percent_off =  100 - Math.round( (item['price'] / item['list_price']) * 100 );
		var list_price = item['list_price'];
		var sale_price = item['price'];

		var list_price_display = '<span class="list-price">' + format_price(list_price) + '</span>';
		list_price_display += ' <span class="sale-price">' + format_price(sale_price) + '<br/>' + percent_off + '% Off </span>';

		item['price'] = list_price_display;
	}else{
		item['price'] = format_price(item['price']);
	}
	
	if(item['preorder_text'] != null){
		item['preorder_text'] = '<span class="preorder-text">' + item['preorder_text'] + '</span>';
	}else{
		item['preorder_text'] = '';
	}
	
	return item;
}

/* This function updates all html tags with class "saleprice" with the wholesale price, if applicable */
function update_ws_prices(){
	if($.cookie("isWholesale") == "true"){
		$('.saleprice').each(function(){
			var wsprice = $(this).attr('wsprice');
			if(wsprice != ""){
				$(this).html(wsprice);
			}
		});
	}
} 

/*
 * Hardcoded function that performs the following
 * This function was written to display a CMS page originally written to be
 * content of a facebox dialog
 * 1. If element with elementID is visible hide it
 * 2. Execute an AJAX JSONP request for url
 * 3. Merge result with element with templateID using jquery template
 * 4. Remove the element with the detachSelector (In this case I use it remove 
 * the CLOSE anchor.)
 * 5. Show the merged element with elementID
 */
function jsonp_show(url, templateID, elementID, detachSelector)
{
	if($('#' + elementID).css('display') == 'block')
	{
		$('#' + elementID).hide();
	}
	else
	{
		$.ajax
		(
			{
				url: url,
				data: 
				{ 
					'randid' : Math.random() 
				},
				dataType: 'json',
				success: function(data)
				{
					var output = $('#' + templateID).tmpl(data);
					$('#' + elementID).html(output);					
					$(detachSelector).detach()
					$('#' + elementID).show();
					popup_tweaks();
				}
			}
		);
	}
}


function submitEmailRegistration(url)
{
	$('#submitEmailRegistrationError').empty();
	$.ajax
	(	
		{
			url: url,
			data: 
			{ 
				'randid' : Math.random(),
				'action' : 'ADD_NOACCT_Subscription',
				'success': '/views/success_empty.jsp',
				'failure': '/views/failure_empty.jsp',
				'email_subscription_type_refcode' : 'signup',
				'email_address' : $('#email').val()
			},
			dataType: 'jsonp',
			success: function(data)
			{
				if(!data.successfully_submitted)
				{					
					for(var idx = 0; idx < data.errors.length; idx++)
					{
						$('#submitEmailRegistrationError').append('<p style="color:red;">' + data.errors[idx] + '</p>');
					}
				}
				else
				{
					$('#submitEmailRegistrationError').append('<p>Thank you for registering</p>');
				}
			}
		}
	);
}

function format_price(price) {
	price = price.toFixed(2) + '';
	x = price.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;
}
		
