/*
NOTE: The valid() function wasn't working under jQuery 1.3.1
*/

var USE_SECURE = ("https:" == document.location.protocol);

// set up constants for page mode
var PAGE_MODE_PAGES = "pages";
var PAGE_MODE_PROBLEMS = "problems";
var PAGE_MODE_SLIDES = "slides";

var validator; // validator object so we can get number of invalids after valid() call
var defaultNotes="Enter as much information as possible here so we can accurately process your order; we have plenty of room!";
var formInit=false;
var pageMode=PAGE_MODE_PAGES; // default is "pages"
var lastBuyback="NULL"; // remeber buyback when we hide/show it... we need to set to NULL when we hide the select, otherwise it'll get sent via ajax
var pricingFieldsSelector = "#atype_id, #edlevel_id, #subject_id, #job_pages, #job_isproblems, #job_sources, #job_islegalmed, #job_ukdialect, #job_buybackdays, #deadline_m, #deadline_d, #deadline_y, #deadline_h, #deadline_i, #deadline_s, #deadline_a, #job_discountcode, #job_email"; // fields used to evaluate price (#job_email was added for discount re-use checking)
// two shortcuts for price floater function
var $window;
var $price_float;

function fadeField(selectElement, affectedSelector){
	if(formInit){
		// use effects
		($(selectElement).val() == "NULL") ? $(affectedSelector).fadeIn() : $(affectedSelector).fadeOut();
	}else{
		// show/hide
		($(selectElement).val() == "NULL") ? $(affectedSelector).show() : $(affectedSelector).hide();
	}
}


function pageModeChanged(){
	// change "pages" text to "problems"
	// note that the tooltip must be called again after changing the title attr of label
	switch(pageMode){
		case PAGE_MODE_PROBLEMS:
			$("#wordcount").hide();
			$("#job_pages_label").text("Number of Problems:").attr("title", "The number of math or statistics problems to be solved");
			$("#job_pages_label").tooltip({track: true});
			$("#job_isproblems").val("1");
			break;
			
		case PAGE_MODE_SLIDES:
			$("#wordcount").hide();
			$("#job_pages_label").text("Number of Slides:").attr("title", "The number of PowerPoint slides to be developed");
			$("#job_pages_label").tooltip({track: true});
			$("#job_isproblems").val("0");
			break;
			
		case PAGE_MODE_PAGES:
		default:
			$("#wordcount").show();
			$("#job_pages_label").text("Number of Pages:").attr("title", "The number of pages the paper should be - all papers are 300 words per page, double-spaced, 12pt Times New Roman");
			$("#job_pages_label").tooltip({track: true});
			$("#job_isproblems").val("0");
	}
	
}


function updatePricing(){
	$("#price_cell").html("Calculating price...");
	var dataStr = $(pricingFieldsSelector).serialize();
	var urlPre = (USE_SECURE) ? "https://secure." : "http://www.";
	$.ajax({
		type: "POST",
		url: urlPre+"powerpapers.com/pricing_engine/from_orderform/",  // MUST HAVE TRAILING SLASH!
		cache: false,
		data: dataStr,
		dataType:"json",
		success: function(data){
			if(typeof(data) != "object"){
				$("#price_cell, #price_float_inner").html(data);
				return;
			}
			
			// build html
			if(data.error.length){
				$("#price_cell, #price_float_inner").html('<p class="price_error">'+data.error+'</p>');
			}else{
				$("#price_cell, #price_float_inner").html("");
				$("#price_cell, #price_float_inner").append('<p class="price noMargin">'+data.price+'</p>');
				if(data.warning.length) $("#price_cell").append('<p class="price_warning">NOTE: '+data.warning+'</p>');
				if(data.breakout.length) $("#price_cell").append('<p class="price_breakout"><strong>Pricing Breakout:</strong><br/>'+data.breakout+'</p>');
				if(data.discount.length) $("#price_float_inner").append('<p><em>You save '+data.discount+'!</em></p>');
			}
			
		}
	});

}

function movePriceFloat(animate){
	var threshold = 300;
	var offset = ($window.height() - $price_float.height())/2;
	var pos = ($window.scrollTop() + offset < threshold) ? threshold : $window.scrollTop() + offset;
	
	 $price_float.stop();
	 if(animate){
		 $price_float.animate({marginTop: pos});
	 }else{
		 $price_float.css({marginTop: pos});
	 }
	 
}

$(document).ready(function(){
	// enable us to disable options across all browsers, see http://harrybailey.com/2008/11/disabling-select-options-in-internet-explorer/
	$.fn.extend(
	{
		optionDisable:function()
		{
			var ths = $(this);
			if(ths.attr('tagName').toLowerCase() == 'option')
			{
				ths.before($('<optgroup>&nbsp;</optgroup>').css({color:'#ccc',height:ths.height()}).attr({id:ths.attr('value'),label:ths.text()})).remove();
			}
			return ths;
		},
		optionEnable:function()
		{
			var ths = $(this);
			var tag = ths.attr('tagName').toLowerCase();
			if(tag == 'option')
			{
				ths.removeAttr('disabled');
			}
			else if(tag == 'optgroup')
			{
				ths.before($('<option />').attr({value:ths.attr('id')}).text(ths.attr('label'))).remove();
			}
			return ths;
		}
	});
	
	// price floater
	$price_float = $('<div id="price_float"><div class="top"></div><div class="mid"><h3><strong>Your Price:</strong></h3><div id="price_float_inner"></div><br /></div><div class="bottom"></div></div>');
	$price_float.prependTo('body');
	$window = $(window);
	$window.scroll(function(){ movePriceFloat(true); });
	movePriceFloat(false);
	
	// calendar
	Date.format = 'mm-dd-yyyy'; // lame american date format
	// restrict to future dates up to n months
	
	$('#cal').datePicker({
		createButton:false,
		startDate:(new Date()).asString(),
		endDate:(new Date()).addMonths(12).asString()
	})
	.bind('dateSelected', function(e, selectedDate){
		var d = selectedDate.asString();
		var a = d.split("-");
		$("#deadline_m").val(a[0]);
		$("#deadline_d").val(a[1]);
		$("#deadline_y").val(a[2]);
		var f = updatePricing; // don't know why I need to do this...
		f();
	})
	.bind('click', function(){
				$(this).dpDisplay();
				this.blur();
				return false;
	});
	
	// tooltips
	$("label").tooltip({
		track: true
	});
	
	// set up textarea. Remember to use e.attr("value") instead of e.val() for textareas
	if($("#orderform #job_notes").attr("value") == "") $("#orderform #job_notes").attr("value", defaultNotes);
	// textarea change
	$("#orderform #job_notes")
	.css("height", "35px")
	.attr("className", "blurred")
	.focus( function(){
		if($(this).attr("value") == defaultNotes) $(this).attr("value", "");
		$(this).attr("className", "").animate( { height:"300px" }, 300 );
	})
	.blur( function(){
		if($(this).attr("value") == "") $(this).attr("value", defaultNotes);
		$(this).attr("className", "blurred");
		$(this).animate( { height:"35px" }, 500 );
	});
	
	
	// pageMode behavior (will trigger later)
	$("#atype_id").change( function(){
		var prevMode = pageMode;
		switch($(this).val()){
			case "20":
			case "34":
				pageMode = PAGE_MODE_PROBLEMS;
				break;
			case "42":
				pageMode = PAGE_MODE_SLIDES;
				break;
			default:
				pageMode = PAGE_MODE_PAGES;
		}
		if(prevMode != pageMode) pageModeChanged();
	});
	
	// buyback show/hide behavior (will trigger later)
	$("#atype_id").change( function(){
		var showSelect = ($("option:selected", this).attr("className") == "buybackable") ? 1 : 0;
		if($("#job_buybackdays:visible").length == showSelect) return; // don't run if state matches hide/show already (it will overwrite lastBuyback var)
		(showSelect) ? $("#buyback_disabled_msg").hide() : $("#buyback_disabled_msg").show();
		if(showSelect){
			$("#job_buybackdays").show().val(lastBuyback);
		}else{
			lastBuyback = $("#job_buybackdays").val();
			$("#job_buybackdays").hide().val("NULL"); // set to NULL for ajax
		}
	});
	
	// disable education levels for certain assignment types
	$("#atype_id").change( function(){
		switch($(this).val()){
			case "13": // journal article
			case "11": // dissertation
				$("#edlevel_id").val("3"); // change to PhD
				if($('#edlevel_id').children("[value='2']").length) $('#edlevel_id').children("[value='2']").optionDisable(); // disable masters
				// no break
			case "12": // proposal
			case "10": // thesis
			case "41": // action research project
			case "43": // capstone project
			case "62": // KAM
				// select other edlevel if necessary
				switch($("#edlevel_id").val()){
					case "5": // HS
					case "1": // undergrad
						$("#edlevel_id").val("2"); // change to masters
						break;
				}
				// disable HS & Undergrad... must check length before or error will occur (element transformed into optgroup & loses ID)
				if($('#edlevel_id').children("[value='1']").length) $('#edlevel_id').children("[value='1']").optionDisable();
				if($('#edlevel_id').children("[value='5']").length) $('#edlevel_id').children("[value='5']").optionDisable();
				break;
			default:
				// enable all edlevels
				$('#edlevel_id').children().each(function() {
					$(this).optionEnable();
				});
		}
	});
	
	// show/hide behaviors
	$("#atype_id").change( function(){
		fadeField(this, "#job_atypeother_row");
	}).trigger("change");
	$("#subject_id").change( function(){
		fadeField(this, "#job_subjectother_row");
	}).trigger("change");
	$("input[name='job_sourcesincluded']").click(function(){
		$("#job_sourcesincluded_writer").is(":checked") ? $("#job_sourcesincluded_writer_small").show() : $("#job_sourcesincluded_writer_small").hide();
		$("#job_sourcesincluded_upload").is(":checked") ? $("#job_sourcesincluded_upload_small").show() : $("#job_sourcesincluded_upload_small").hide();
	});
	
	
	// pricing update triggers
	$(pricingFieldsSelector).change(function(){
		updatePricing(this);
	});
	
	// word counter
	$("#job_pages").change(function(){
		if(pageMode != PAGE_MODE_PAGES) return;
		var pages = parseFloat($(this).val());
		if(pages > 0 && pages <= 200) $("#wordcount").text("Word count: "+number_format(pages*300, 0)+" (300 words per page)");
	}).trigger("change");
	
	// style file browse inputs
	/*
	$("input[type=file]").filestyle({ 
		image: "images/button_choose_file.jpg",
		imageheight : 25,
		imagewidth : 86,
		width : 250
	});
	*/
	
	// prevent submit on enter key
	$("input").keypress(function(e) {
		if(e.keyCode == 13){
			if(typeof(e.preventDefault) != "undefined") e.preventDefault();
			if(typeof(e.stopPropagation) != "undefined") e.stopPropagation();
			return false;
		}
	});
	
	// prevent double-submit
	$('form').submit(function(){
		$(':submit, :image', this).click(function() {
			return false;
		});
	});
	
	// set up validation
	validator = $("#orderform").validate({
		errorElement: "em",
		rules:{
			job_email: {
				required:true,
				email:true
			},
			
			atype_id:{
				required:true
			},
			
			job_atypeother: {
				required: {
					depends: function(element) {
						return $("#atype_id").val() == "NULL";
					}
				}
			},
			
			subject_id:{
				required:true
			},
			
			job_subjectother: {
				required: {
					depends: function(element) {
						return $("#subject_id").val() == "NULL";
					}
				}
			},
			
			edlevel_id:{
				required:true
			},
			
			job_pages:{
				required:true,
				number:true,
				min:1,
				max:200
			},
			
			job_sources:{
				required:true,
				digits:true
			},
						
			deadline_date:{
				required:true
			},
			deadline_time:{
				required:true
			},
			
			securityAnswer:{
				required:true
			}
		}
	});
	
	$("#imagesubmit").click(function() {
		// make sure we can calculate the price
		if($("#price_error").val() != "0"){
			alert("Plese fix this error before continuing: "+$("#price_error").val());
			return false;
		}
		
		if($("#orderform").valid()){
			// make sure user want to submit w/o instructions...
			
			if( $("#orderform #job_notes").val() == defaultNotes || $("#orderform #job_notes").val().length == 0){
				var ok = confirm("Are you sure you don't want to send us the full instructions for your project? The more information we have, the better we can meet your needs. Click ok to continue, or cancel to return to the form.");
				if(!ok){
					$("#job_notes").trigger("focus");
					return false;
				}
			}
			// remove default text if it's still in there
			if( $("#orderform #job_notes").val() == defaultNotes ) $("#orderform #job_notes").val("");
			return true
		}else{
			alert(validator.numberOfInvalids()+" field(s) need to be corrected before continuing.");
			return false;
		}
	});
	
	formInit = true;
	$("#loader").hide();
	// don't use visibility CSS, it will show all nested hidden items when set to visible.
	$("#formtableholder").show();

});
