$(document).ready(function() {
	$('.noepop').click(function() {
		return recapture_qd();
	});
	
	/*
	var sh = $(window).height();
	var sw = $(window).width();
	$.each($('a.thickbox'), function(i, val) {
		var h = $(this).attr('href');
		var base = h.substring(0, h.indexOf('?'));
		var newh = h.substring(h.indexOf('?')+1, h.length).split("&");
		var qstr = new Array;
		var y = 0;
		for(var x=0; x<newh.length; x++) {
			var separator = newh[x].indexOf('=');
			if(newh[x].substring(0, separator) == "width") {
				var oldwidth = newh[x].substring(separator + 1);
			} else if(newh[x].substring(0, separator) == "height") {
				var oldheight = newh[x].substring(separator + 1);
			} else {
				qstr[y] = newh[x];
				y++;
			}
		}
		newwidth = oldwidth;
		newheight = (sh > 400 ? sh - 120 : 400);
		qstr[y] = "width=" + newwidth + "&height=" + newheight;
		var newurl = base + "?" + qstr.join("&");
		alert(newurl);
		// $(this).attr('href', newurl);
	});
	
	$('div#TB_window').live('load', function() {
		var ctop = $(this).css('margin-top');
		$(this).css('margin-top', ctop - 20);
		alert(ctop + "\n" + $(this).css('margin-top'));
	});
	*/
});

var player;
function playerReady(obj) {
	player = document.getElementById(obj['id']);
	addListeners();
	if(window.playerready2) {
		playerready2();
	}
}

function stateListener(obj) {
	if(obj.newstate == "COMPLETED") {
		player.sendEvent("STOP","true");
	}
}

function addListeners() {
	if(player) {
		player.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()",100);
	}
}

var exit_pop;
var exit_pop_url;
var form_vals = new Array();
var form_elements = $('#billingform input, #billingform select');
function recapture() {
	if(location.search.indexOf('nep') == -1) {
		exit_pop = 0;
		exit_pop_url = location.href;
		var form_elements = $('#billingform input, #billingform select');
		
		$(window).unload(function() {
			var email = $('#id_email');
			var phone = $('#id_phone');
			if((email.val().length < 1 || !validateEmail(email.val())) && (phone.val().length < 1 || !validatePhone(phone.val()))) {
				$.each(form_elements, function(i, elem) {
					form_vals[i] = $(elem).attr('name') + ':' + $(elem).val();
				});
				var prot = location.protocol + '//';
				var host = location.host;
				var pop_width = 550;
				var pop_height = 350;
				var pop_left = (screen.width / 2) - (pop_width / 2);
				var pop_top = (screen.height / 2) - (pop_height / 2);
				window.open(
					prot+host+'/flare/next?_pg_response_=exitpop&form_vals='+form_vals,
					'exit_pop',
					'height='+pop_height+', width='+pop_width+', top='+pop_top+', left='+pop_left+', resizable=1, scrollbars=1'
				);
			}
		});
	} else {
		alert('nep found. no exit pop');
	}
}

function recapture_qd() {
	$(window).unbind('unload');
	return true;
}

function endpage_loaded() {
	$.post("end");
}

function reset_site() {
	$.ajax({
	 type: "POST",
	 url: "/flare/end-debug",
	 async: false,
	 cache: false
	});
	return true;
}

function keepMeAlive() {
	if (typeof(pingTime) != 'undefined') {
		pingTime.setMinutes(pingTime.getMinutes() + 15);
		// if more than 15 min passed from last ping, reset everything
		currentTime = new Date();
		if (currentTime > pingTime) {
			pingcount = -1;
		}
	}
	// reset time to current date
	pingTime = new Date();
	if (pingcount == -1) {
		// do nothing...
	} else if (pingcount >= 15) {
		// session timed out
		pingcount = -1;
		window.location.href = "timedout.html";
	} else {
		$.post("ping");
		pingcount++;
	}
}

function keepMeAliveLanding() {
	if (typeof(pingTime) != 'undefined') {
		pingTime.setMinutes(pingTime.getMinutes() + 15);
		// if more than 15 min passed from last ping, reset everything
		currentTime = new Date();
		if (currentTime > pingTime) {
			pingcount = -1;
		}
	}
	// reset time to current date
	pingTime = new Date();
	if (pingcount == -1) {
		// do nothing...
	} else if (pingcount >= 30) {
		// session timed out
		pingcount = -1;
		window.location.href = "timedout.html";
	} else {
		$.post("ping");
		pingcount++;
	}
}

function updateQty(item_num) {
	// Calculate new total for this item
	old_total = parseFloat($("#total_price_" + item_num).text());
	new_qty = parseInt($("#item_qty_" + item_num + " select").val());
	unit_price = parseFloat($("#unit_price_" + item_num).text());
	unit_ship = parseFloat($("#shipping_" + item_num).text());
	if (isNaN(unit_ship)) {
		new_total = new_qty * unit_price;
	} else {
		new_total = new_qty * (unit_price + unit_ship);
	}
	$("#total_price_" + item_num).text(new_total.toFixed(2));

	// Clear tax and shipping for now
	total_shipping = parseFloat($("#total_ship_price").text());
	if (isNaN(total_shipping)) {
		total_shipping = 0;
	}

	$("#total_ship_price").text("TBD").addClass("tbd");
	total_tax_due = parseFloat($("#total_tax_price").text());
	if (isNaN(total_tax_due)) {
		total_tax_due = 0;
	}
	$("#total_tax_price").text("TBD").addClass("tbd");

	$(".bonus_items").parent().siblings(".price").text('TBD').addClass("tbd");

	// Calculate new grand total (independent of tax & shipping)
	old_grand_total = parseFloat($("#total_amount").text());
	new_grand_total = old_grand_total - old_total - total_shipping - total_tax_due + new_total;
	$("#total_amount").text(new_grand_total.toFixed(2));
	$("#total").html('Total Amount<br><span class="tbd">plus shipping & applicable taxes</span>');
}

function qty_select_changed(){
	var parent_id = $(this.parentNode).attr("id");
	num = parent_id.replace("item_qty_","");
	updateQty(num);
}

function sendToFriend() {
	sendFrom = $('#mtaf-box-from').val();
	sendTo = $("#mtaf-box").val();
	if(!validateEmail(sendFrom) || !validateEmail(sendTo)) {
		$('#mtaf-errors').html('Please complete the form before sending.');
		return false;
	}
	$('#mtaf-cancel').hide();
	$('#mtaf-send').val('Sending...').attr('disabled','true');
	$.ajax(
		{
			type: "POST",
			url: "ajax-email/",
			data: "sendto=" + sendTo + "&sendfrom=" + sendFrom,
			success: function () {
				hide_mtaf();
		 		$("#mtaf").html("&bull;&nbsp;&nbsp;Message sent to " + sendTo);
		 		$("#mtaf").css("font-style","italic");
			}
		}
	);
	return false;
}

function setup_mtaf() {
	$("#mtaf-form label").inFieldLabels();
	$("#mtaf-form").submit(sendToFriend);
	$("#mtaf-cancel").click(hide_mtaf);
	$("#mtaf-box, #mtaf-box-from").focus(function() {
		if ($(this).attr("def") == "1") {
			$(this).val("");
			$(this).attr("def","0");
		}
		$('#mtaf-errors').html('');
	});
	$("#mtaf-form").validate();
}

function show_mtaf() {
	tb_show('', '#TB_inline?height=220&width=450&inlineId=mtaf-container&modal=true', null);
	return false;
}

function hide_mtaf() {
	$('#TB_ajaxContent form')[0].reset();
	$('#mtaf-box-from, #mtaf-box').blur();
	$('#mtaf-form label.error').hide();
	tb_remove();
	return false;
}

function spartial() {
	var data_fields = ["name_first", "name_last", "address_1", "address_2",
					   "city", "state", "country", "postalcode",
					   "phone", "email"];
	var field_val;
	var a = [];
	for (var f in data_fields) {
		field_val = $.trim($("#id_" + data_fields[f]).val());
		if (field_val) {
			a.push(data_fields[f] + "=" + field_val);
		}
	}
	if (a.length <= 2) {
		// not enough data to send
		return;
	}
	if (sparcount <= 10) {
		$.ajax(
			{
				type: "POST",
				url: "spartial/",
				data: a.join("&")
			}
		);
	}
	sparcount++;
}

function manage_cvv_field() {
	if($('#id_card_type').val() == 'Discover') {
		$('.card_verification_div,#cvv_label_cell,#cvv_field_cell').show();
	} else {
		$('.card_verification_div,#cvv_label_cell,#cvv_field_cell').hide();
	} 
}

function function_exists(function_name) {
	if(typeof function_name == 'string') {
		return (typeof window[function_name] == 'function');
	} else {
		return (function_name instanceof Function);
	}
}

function WLpopup() {
	var args = 'height=' + (screen.availHeight - 50 ) + ',width=' + (screen.availWidth - 10) + ',left=' + 0 + ',top=' + 0 + ',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1';
	var winPop = window.open("wlp.html", "wl_pop", args);
	winPop.blur();
}

function WLpopupUpsell() {
	$(window).bind("unload", function() {
		$.post("wle");
		var args = 'height=' + (screen.availHeight - 50 ) + ',width=' + (screen.availWidth - 10) + ',left=' + 0 + ',top=' + 0 + ',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1';
		var winPop = window.open("wlp.html", "wl_pop", args);
		winPop.focus();
	});
}

function WLpopupConfirm() {
	$.post("wle");
	var args = 'height=' + (screen.availHeight - 50 ) + ',width=' + (screen.availWidth - 10) + ',left=' + 0 + ',top=' + 0 + ',toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1';
	var winPop = window.open("wlp.html", "wl_pop", args);
	winPop.focus();
}

function WLpopupDisable() {
	$(window).unbind("unload");
}

function applyQAS() {
	$('#billingform').queue(function() {
		$(this).after('<input type="button" id="input_search" value="" style="display:none;" />')
						 .wrap('<div id="proweb_wgt"></div>')
						 .before(
							'	<input type="hidden" id="AJAXURL" value="sites/prowebproxy.xml" />' +
							'	<input type="hidden" id="ADDRESSLAYOUT" value="Database layout" />' +
							'	<input type="hidden" id="RUN_AS_POPUP" value="true" />' +
							'	<input type="hidden" id="IGNORE_UNMATCHED_ADDRESSES" value="false" />' +
							'	<input type="hidden" id="IGNORE_CONNECTION_ERROR" value="true" />' +
							'	<input type="hidden" id="BYPASS_QAS_VERIFICATION" value="false" />' +
							'	<!-- for proweb js compatibility. to be removed later. -->' +
							'	<input type="hidden" id="linethree" type="text" />' +
							'	<!-- This is the name of id attribute of the submit button for the page form -->' +
							'	<input type="hidden" id="FORM_BUTTON_ID" value="the_submit_button" />' +
							'	<input type="hidden" id="QASMatched" name="QASMatched" value="false" />')
						 .wrap('<div id="input_wgt" class="proweb"></div>');
		$(this).dequeue();
	});
	$('head').queue(function() {
		$(this).append(
			'<link rel="stylesheet" type="text/css" href="css/proweb.css" />' +
			'<script type="text/javascript" src="js/proweb.js"></script>'
		);
		$(this).dequeue();
	});
	return true;
}

