/*
------------------------
Cart/Checkout JavaScript
(c) Shoebuy.com, Inc.
------------------------
*/

/*
 This extends jquery so that you can create a counter for inputs that have a maximum length
 eg. $('#some_id_of_textarea').counter()
 the following options can also be defined:

 counter_text -- this is the text defined after the number of characters default is characters left
 max_length -- this is the maximum characters of the field default is 250

*/
if (typeof(jQuery) != "undefined") {
	(function($) {
		$.fn.counter = function(options) {
			var defaults = {
				counter_text: 'characters left',
				max_length: 250
			};
			var opts = $.extend(defaults, options);

			var $this = $(this);
			$this.after('<p><span class="counter"></span> ' + opts.counter_text + '</p>');
			$this.parent().find('.counter').html(opts.max_length - $this.val().length);
			$this.keyup(function(e) {
				$(e.target).parent().find('.counter').html(opts.max_length - $(this).val().length);
			});
		}
	})(jQuery);
}

function popup(url, height) {

	if (!height) {
		height = 560;
	}
	var params = 'width=525,height=' + height + ',dependent=1,resizable=1,scrollbars=1';
	newwindow=window.open(url,'name',params);
	return false;
}

var stayOffer = true;
if (document.URL.indexOf("/cust") > 0 && ("$in{OrderID}".length == 0 || "$in{myaction}" == "checkoutLogin")) {
	stayOffer = false;
} else if( document.URL.indexOf("/cart") > 0 && "$in{checkout}".length == 0) {
	stayOffer = false;
}

// Retrieve the value of the cookie with the specified name.
function GetCookie(sName) {
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++) {
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0])
			return unescape(aCrumb[1]);
	}

	// a cookie with the requested name does not exist
	return null;
}

function notOffer() {
	stayOffer = false;
}

function setOnClicks(widget) {
	var links;
	var link_arr = document.links;
	var numlinks = link_arr.length;
	for (var iter = 0; iter < numlinks; iter++) {
		var mylink = link_arr[iter];
		var l_action = mylink.href;
		if (l_action.indexOf("javascript") != 0 && l_action.indexOf("shoebuy.com/") > 0 && !mylink.onclick) {
			 mylink.onclick = notOffer;
		}
	}

	link_arr = document.forms;
	for (var iter = 0; iter < link_arr.length; iter++) {
		if (link_arr[iter].name != "internationalCheckoutForm") {
			link_arr[iter].onsubmit = notOffer;
		}
	}
}

function pleaseStay(popupUrl) {
	if (GetCookie('id') == null || GetCookie('seenLeaveCart') != null || GetCookie('thispromo') != null) {
		stayOffer = false;
	}

	if (stayOffer) {
		var coords = "";
		var winx = window.screenLeft; // + 10; 
		var winy = window.screenTop;// + 10;
		if (winx != null && winy != null) {
			winx += 10;
			winy += 10;
			coords = 'left=' + winx + ',top=' + winy + ',';
		}
		if (popupUrl == undefined)
			popupUrl = '/exitPopup.html';
		var newmp = window.open(popupUrl, 'marketingPopup',coords + 'width=1,height=1,location=0,toolbar=0,status=0,menubar=0');
		window.focus();
	}
}

function setBML90dayOffer() {
	var offer_text = document.getElementById("bml90_text");
	var bml_radio = document.getElementById("paymentType_bml");

	if (bml_radio && offer_text) {
		if (bml_radio.checked) {
			offer_text.style.cssText = "color:black;display:inline;";
			document.getElementById("bml90day_checkbox").disabled=false;
		} else {
			offer_text.style.cssText = "color:gray;display:inline;";
			document.getElementById("bml90day_checkbox").disabled=true;
		}
	}
}

function goBorderFree() {
	var exp_date = new Date();
	notOffer(); //Don't offer exitpop '
	document.cookie = "id=''; path=/; expires=" + exp_date.toGMTString();
	return true;
}

var contact_first;
var contact_last;
var billing_first;
var billing_last;

function correctFormValueSync() {
	if(contact_first.val() !== billing_first.val()) {
		contact_first.val(billing_first.val());
	}
	if(contact_last.val() !== billing_last.val()) {
		contact_last.val(billing_last.val());
	}
}

function swapContactFieldsJQ() {
	contact_first = $('input#contact_firstname');
	contact_last = $('input#contact_lastname');
	var contact_email = $('input#contact_email');
	var contact_phone = $('input#PhoneNumber');
	var contact_cust = $('input#contact_cust_id');
	billing_first = $('input#billing_firstname');
	billing_last = $('input#billing_lastname');
	var billing_email = $('input#billing_email');
	var billing_phone = $('input#billing_phonenumber');
	var billing_cust = $('#billing_cust_id');
	if(contact_first.length==1 && contact_last.length==1 && contact_email.length==1 && contact_phone.length==1 && billing_first.length==1 && billing_last.length==1 && billing_email.length==1 && billing_phone.length==1) {
		billing_first.change(function(){
			contact_first.val(this.value);
		});
		billing_last.change(function(){
			contact_last.val(this.value);
		});
		billing_email.attr('name',contact_email.attr('name'));
		contact_email.attr('name','contact_email');
		billing_phone.attr('name', contact_phone.attr('name'));
		contact_phone.attr('name', 'contact_phone');
		if(contact_cust.length==1 && billing_cust.length==1) {
			billing_cust.attr('name', contact_cust.attr('name'));
			contact_cust.attr('name', 'contact_cust_id');
		}
		$('input.continue_button').click(correctFormValueSync);
	}
}

function deliveryBeforeShow(brandId, suffix) {
	var brand = brands[brandId];
	return function(i) {
		if (brand['ground']) {
			$("#nonspecific" + suffix).attr("checked", false);
			$("#specific"	+ suffix).attr("checked", true);
		}
		return {};
	}
}

function deliveryCost(brandId, prodId, date) {
	var brand = brands[brandId], prod = prods[prodId], cost = -1;

	if (new Date() < getLocalDelivCutoff(brand['cutoff'], tzOffset) || brand['costAC'][date] == undefined)
		cost = brand['costBC'][date];
	else
		cost = brand['costAC'][date];

	if (prod && !prod[date])
		cost = -1;

	return cost
}

function deliveryBeforeShowDay(brandId, prodId) {
	return function(d) {
		var cost = deliveryCost(brandId, prodId, $.datepicker.formatDate('yymmdd', d));

		return cost < 0 ? [false,""] : [true,"datepicker-ship-" + cost];
	}
}

function deliveryOnSelect(itemId, brandId, prodId) {
	var origDate = '', origCost = 0, item = items[itemId];
	if (item) {
		if (item[0] != 'ground') origDate = $.datepicker.formatDate('D, M d', $.datepicker.parseDate('mm/dd/yy', item[0]));
		origCost = item[1];
	}

	return function(dateText, inst) {
		if (dateText != origDate) {
			var msg = $('#warn_msg_'+itemId);
			if (msg && msg.length > 0) {
				$('#warn_img_'+itemId).remove();
				var span = $('#warn_span_'+itemId);
				span.attr('rowspan', span.attr('rowspan') - 1);
				msg.remove();
			}
			if (document.page_form) {
				var cost = deliveryCost(brandId, prodId, $.datepicker.formatDate('yymmdd', $.datepicker.parseDate('D, M d', dateText)));
				if (cost != origCost)
					document.page_form.submit();
			}
		}
	}
}

function deliveryOnChangeMonthYear(brandId) {
	var brand = brands[brandId];

	return function(year, month, inst) {
		var timer = setInterval(function() {
			if ($('#date-legend').length == 0)
				$('#ui-datepicker-div').append('<div id="date-legend"><div id="date-legend-header">Shipping Cost Legend</div><table align="left">' + brand['legend'] + '</table></div>');
			clearInterval(timer);
		}, 10);
	}
}

function deliveryDateInit(itemId, brandId, prodId, multiple, deliveryHorizon) {
	var suffix = multiple ? "_" + itemId : "";
	if (deliveryHorizon == undefined) deliveryHorizon = 31;

	$(function() {
		var picker = $("#DatePicker"+suffix), hidden = $("#RequestedDate"+suffix), item = items[itemId];
		if (item && item[0] != 'ground') {
			var dateVal = $.datepicker.parseDate('mm/dd/yy', item[0]);
			picker.val($.datepicker.formatDate('D, M d', dateVal));
			if (brands[brandId]['ground']) {
				$("#nonspecific" + suffix).attr("checked", false);
				$("#specific"	+ suffix).attr("checked", true);
			}
		}
		var onSelect_fn = deliveryOnSelect(itemId, brandId, prodId);
		picker.datepicker({minDate: '0', maxDate: '+' + deliveryHorizon , dateFormat: 'D, M d', altField: "#RequestedDate"+suffix, altFormat: 'yymmdd', beforeShowDay: deliveryBeforeShowDay(brandId, prodId), onSelect: onSelect_fn, beforeShow: deliveryBeforeShow(brandId, suffix), onChangeMonthYear: deliveryOnChangeMonthYear(brandId)});
		picker.click(deliveryOnChangeMonthYear(brandId));
		if (picker[0].value && picker[0].value != "Select a date") { // Fix back/forward browser issues.
			onSelect_fn(picker[0].value);
		}
	});
}

