if(typeof(console) === "undefined") {
    console = { log: function() { } };
}

$(document).ready(function() {
	$('.noepop').click(function() {
		return recapture_qd();
	});
});

$('#billingform').ready(function() {
	if(location.search.indexOf('billing_form') != -1) {
		$('#displayerrors, .validationtext').text('');
	}
});



// FOLLOWING 3 FUNCTIONS ALLOW FOR JW PLAYER REFERENCES
var mplayers = new Array();
function playerReady(obj) {
    var player = document.getElementById(obj['id']);
    var idx = mplayers.push(player) - 1;
    addListenersMulti(idx);
    if(window.playerready2) {
        playerready2();
    }
}

function stateListener(obj) {
	if(obj.newstate == "COMPLETED") {
		obj.sendEvent("STOP", "true");
	}
}

function addListenersMulti(idx) {
	if(mplayers[idx]) {
		mplayers[idx].addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners("+idx+")", 100);
	}
}



var exit_pop;
var exit_pop_url;
var form_vals = new Array();
var form_vals2 = 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) {
					var elname = $(elem).attr('name');
					form_vals2[i] = elname + ':' + $(elem).val();
					if(elname.indexOf('post_') == -1 && elname.indexOf('pre_') == -1 && 
					   elname.indexOf('option_') == -1) {
						if(elname.indexOf('order_item') == -1 || (elname.indexOf('order_item') != -1 && $(elem).attr('checked'))) {
							form_vals[i] = elname + ':' + $(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+pre_path()+'/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(pre_path()+"/flare/end");
	return true;
}

function reset_site() {
	$.ajax({
	 type: "POST",
	 url: pre_path()+"/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 = pre_path()+"/flare/timedout";
	} 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 = pre_path()+"/flare/timedout";
	} else {
		$.post("ping");
		pingcount++;
	}
}

function pre_path() {
    var path_parts = location.pathname.toLowerCase().split('/');
    if(path_parts[1] != "flare") {
        return "/"+path_parts[1];
    }
    return "";
}

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() {
            $.fn.colorbox.close();
            $("#mtaf").html("&bull;&nbsp;&nbsp;Message sent to " + sendTo);
            $("#mtaf").css("font-style","italic");
        }
    });
	return false;
}

function show_mtaf() {
    $.fn.colorbox({
        inline:true,
        href:'#mtaf-form',
        height:'190px',
        preloading:false,
        overlayClose:false,
        open:true,
        width:'450px',
        title:'Send To A Friend:',
        html:false,
        opacity:'0.8',
        onComplete:customize_mtaf,
        onClosed:hide_mtaf
    });
    return false;
}

function customize_mtaf() {
	$('#cboxTitle').addClass('cbox_title_mtaf');
	$("#mtaf-form label").inFieldLabels();
	$("#mtaf-form").submit(sendToFriend);
	$("#mtaf-cancel").click($.fn.colorbox.close);
	$("#mtaf-box, #mtaf-box-from").focus(function() {
		if($(this).attr("def") == "1") {
			$(this).val("");
			$(this).attr("def","0");
		}
		$('#mtaf-errors').html('');
	});
	$("#mtaf-form").validate();
    return false;
}

function hide_mtaf() {
	$('#mtaf-form-container form')[0].reset();
	$('#mtaf-box-from, #mtaf-box').blur();
	$('#mtaf-form label.error').hide();
	$('#cboxTitle').removeClass('cbox_title_mtaf');
	return false;
}

function spartial() {
	if (sparcount > 200) {
		return;
	}
	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").css('display','').show();
		$("#cvv_label_cell").css('display','').show();
		$("#cvv_field_cell").css('display','').show();
		$("#cc_cvv_label").css('display','').show();
		$("#id_card_verification").css('display','').show();
	} else {
		$(".card_verification_div").css('display','none').hide();
		$("#cvv_label_cell").css('display','none').hide();
		$("#cvv_field_cell").css('display','none').hide();
		$("#cc_cvv_label").css('display','none').hide();
		$("#id_card_verification").css('display','none').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(pre_path()+"/flare/wlp", "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(pre_path()+"/flare/wlp", "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(pre_path()+"/flare/wlp", "wl_pop", args);
	winPop.focus();
}

function WLpopupDisable() {
	$(window).unbind("unload");
}

function setup_billingform() {
	$(".freshform").blur(function () {
		checkValid(this);
	});
	$("#id_name_last").blur(function () {
		$("#id_card_name").val($("#id_name_first").val() + " " + $("#id_name_last").val());
	});
	sparcount=0;
	window.setInterval("spartial()", 30000);
	$("#id_email,#id_phone").blur(function () {
		spartial();
	});
	$("#errorbanner").click(function () {
		$("#errorbanner").hide();
	});
}

function hide_error_notice() {
	$("#errorbanner").fadeOut(1200);
}

$("#upsellform").ready(function() {
        $("#upsellform").submit(protect_from_dbclicks);
        $("#upsellform input:submit").click(save_submit_value);
        $("#upsellform input:submit").removeAttr("disabled");
});

$("#dynaform").ready(function() {
        $("#dynaform input:submit").click(save_submit_value);
});

function protect_from_dbclicks() {
        var but = $("#upsellform input:submit");
        but.attr("disabled","disabled");
        
        $("#upsellform").append("<input type='hidden' name='Submit' value='"+button_val+"'>");
        return true;
}

function save_submit_value(event) {
        button_val = $(event.target).val();
        return true;
}

function repop_form() {
    tb_show('', "#TB_inline?height=400&width=650&inlineId=thickbox_form", null);
}

function popform() {
    $(document).ready(function() {
        setTimeout('repop_form()', 500);
    });
}

function autopop() {
    if(location.hash.indexOf('ordernow') != -1) {
        popform();
    }
}

function show_tb_in_parent() {
    window.opener.repop_form();
    setTimeout('window.close()', 500);
    return false;
}


