var winParams = 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=450,height=490,left=40,top=10';
var winParams2 = 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=700,left=40,top=10';

$.extend({
	mustache: function(template, data, partial, stream) {
		if(Mustache && template && data) {
			return Mustache.to_html(template, data, partial, stream);
		}
	}
});

$(function() {
	$('#listmenu li ul li a, .thumb_link').live('touchend', function(e) {
		window.location = $(this).attr('href');
	});
	
    $('p#forgot a').click(function()  { 
        return prepare_lost_password();
    });
	$('#listmenu li').mouseover(function(e) {
        $('#contflyzoom').hide();
        $(this).children('ul').show();
    }).mouseout(function(e) {
        $(this).children('ul').hide();
        $('#contflyzoom').show();
    });
	$('#add_details #shipping_info a').click(function() { show('shipinfo'); return false; });
	$('#add_details #gift_box a').click(function() { show('giftpackage'); return false; });
	$('#add_details #recycled a').click(function() { show('ecostory'); return false; });

	$('.quickview_link').click(function() {
		var region = $(this).attr('id') + 'box';
		$('.papersource_panel').hide();
		show(region);
		return false;
	});
	$('.quickview_next').click(function() {
		var id = parseInt($(this).attr('id').replace(/^product/, '').replace(/_next/, ''));
		show('product' + (id + 1) + '_qvbox');
		hide('product' + id + '_qvbox');
		return false;
	});
	$('.quickview_prev').click(function() {
		var id = parseInt($(this).attr('id').replace(/^product/, '').replace(/_next/, ''));
		show('product' + (id - 1) + '_qvbox');
		hide('product' + id + '_qvbox');
		return false;
	});

	if(!(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i))) {
		$('.product .thumb').mouseover(function() {
			$(this).find('.qvl').css({ background: "#99CCCC"});
			$(this).find('a.quickview_link').css('display', 'block');
		}).mouseout(function() {
   	   		$(this).find('a.quickview_link').hide();
			$(this).find('.qvl').css({ background: 'transparent' });
		});
	}

	$('.ubar a').click(function() {
		$(this).closest('.papersource_panel').fadeOut(100);
		$(this).parent().siblings('.add_message').hide();
		return false;
	});
	$('.qv_details .qty .immortal_n').change(function() {
		check_qty($(this), $(this).attr('id').replace(/^quantity/, ''));
	});
	
	$('.quickview_add_cart').click(function() {
		var sku = this.id;
		var args = '';
		$('input.quantity' + sku).each(function(i, input) {
			args += '&' + $(input).attr('id') + '=' + $(input).val();
		});
		$.ajax({
			url: '/cgi-bin/paper/checkout/add_to_cart',
			cache: false,
			data: args,
			dataType: "json",
			success: function(data) {
				$('#qv_details' + sku + ' .qtyalert').hide();
				if(data.missing_quantity) {
					$('#message' + sku).html('Please enter the quantity you would like to purchase then add to your bag.');
				} else if(data.result) {
					var item_message = data.nitems;
					item_message += data.nitems > 1 ? ' items, $' : ' item, $';
					item_message += data.subtotal.toFixed(2);
					$('#cart_info').html(item_message).show();
					$('.cart_items').show();
					$('#message' + sku).html(data.message).css({ margin: "5px 0px" }).show();
					$('#checkout_qv' + sku).show();
				}
			}
		});
		return false;
	});
	$('#items-in-cart-link').click(function() {
		$('#previously-viewed-item-list').hide();
		$('#items-in-cart').show();
	});
	$('#previously-viewed-item-list-link').click(function() {
		$('#items-in-cart').hide();
		$('#previously-viewed-item-list').show();
	});
});

/* Homepage */
var validate_email = function(email) {
  return /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i.test(email);
};
var validate_zip = function(zip) {
  return /[0-9]{5}/.test(zip);
};
var handle_success = function(data, textStatus) {
  $("#newsletter_signup_form")[0].reset();
  $("#newsletter_signup_message").html("You have been added to our list.");
  $("#newsletter_signup").hide();
};
var handle_error = function(XMLHttpRequest, textStatus, errorThrown) {
  $("#newsletter_signup_message").html("A Server Error Occurred and we are unable to add your email address at this time.");
};
var post_signup = function(email,zip) {
  var message = "";
  var error = false;

  if (!validate_email(email.value)) {
    error = true;
    message += "Invalid email address format.<br />";
  }

  if (!validate_zip(zip.value)) {
    error = true;
    message += "Invalid zip code format.";
  }

  $("#newsletter_signup_message").html(message);
  if (error) return false;

  $.ajax({
 	url:     ajax_news_signup,
    data:    ({ email: email.value, zip: zip.value, todo: 'submit' }),
    type:    "POST",
    success: function() {
  		$("#newsletter_signup_form")[0].reset();
  		$("#newsletter_signup_message").html("You have been added to our list.");
  		$("#newsletter_signup").hide();
	},
    error:   function() {
  		$("#newsletter_signup_message").html("A Server Error Occurred and we are unable to add your email address at this time.");
	}
	});
};

/* Quantity checks on thumb and product detail */
var check_qty = function(input_box, sku) {
    if (input_box.val() > product_inventory[sku]) {
        input_box.val(product_inventory[sku]).focus();
        $('.qtyalert_' + sku).html('Sorry, only ' + product_inventory[sku] + ' in stock, adjusting your quantity.').css('display', 'block');
    }
    return false;
};
var check_dropdown_qty = function(theInput, sku) {
	var qty = theInput.value;
	if (qty > product_inventory[sku] ) {
        $('#qty_alert').html('Sorry, only ' + product_inventory[sku] + ' in stock. Please adjust your quantity.').css('display', 'block');
    } else {
        $('#qty_alert').html('').hide();
	}
    return false;
};
var check_qty_mult = function(theInput,theMax,itemNum) {
	if (theInput.value > theMax )
	{
		theInput.value = theMax;
		theInput.focus();
		$('#qty_alert'+itemNum).html('Sorry, only '+ theMax+' in stock, adjusting your quantity.').css('display', 'block');
	}
	return false;
}

/* Previously Viewed */
var show_div = function(div) {
	$("#previously-viewed-item-list,#items-in-cart").toggle();
};

/* Product detail */
var last_id;
var show_notify = function(sku) {
    popPict = window.open('/cgi-bin/paper/stock_notify.html?notify_sku=' + sku,'notify',winParams);
    popPict.focus();
};
var showZoom = function(sku) {
        linkStr = '/cgi-bin/paper/showzoom.html?sku='+sku;
        popPict = window.open(linkStr,'pszoom',winParams);
        popPict.focus();
};
var showS7Zoom = function(sku) {
        linkStr = '/cgi-bin/paper/s7zoom.html?sku='+sku;
        popPict = window.open(linkStr,'pszoom',winParams2);
        popPict.focus();
};
var highlight_image = function(image) {
    $("#"+last_id).removeClass("img-border-selected");
    $("#"+image).addClass("img-border-selected");
    last_id = image;
};

var show = function(region) {
	var width = $.browser.msie ? $(document).width() : 990;
	//really weird behavior: IE on checkout page is not centering panel
	//so width needs to be set to 990
	if($('#shiprates').length) {
		width = 990;
	}
	var el = $('#' + region);

	var top_posn = $(window).scrollTop() + ($(window).height() - el.height())/2;
	if(top_posn < 0) {
		top_posn = 0;
	}

	el.css({ top: top_posn, left: (width - el.width())/2  }).fadeIn(100);
	return false;
};
var hide = function(region) {
	$('#' + region).fadeOut(100);
	return false;
};


/* Login */
var prepare_login = function(where_from, create_account) {
	var arg = '';
	if( where_from ) {
		arg = '?display_once=1';
	}
	if($('form#cart_contents').length) {
		arg = '?special_location=basket';
	} else if($('form#checkout').length) {
		arg = '?special_location=checkout';
	}
	if(create_account) {
		arg += '&create_account=1';
	}
    $('input#login_where_from').val('login');
	window.open(login_location + arg, "loginbox","location=0,status=0,scrollbars=0,width=405,height=305"); 
    return false;
};

var prepare_lost_password = function() {
    $('div#login').hide();
    $('div#password').show();
    $('div#return_messages').html();
    return false;
};

