/*
 * quote.js
 *
 * This initially retrieves a json object from the server with the covered categories,
 * then makes an additional ajax call to find out the quoted price (Plus informational
 * string)
 *
 */

var cats = null;
var url = site_root + "quotes.php";
// This jq object will be created at the end of jquery.js
// var jq = jQuery.noConflict();
var catsloaded = false;

/*
 * void returnQuote()
 *
 * This is the callback method used after an ajax request for quote.
 * Creates the html that is displayed to the user with the returned
 * data, so this will probably need to be modified slightly to fit
 * with what Pete wants to do.
 */
 
function CurrencyFormatted(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
 
 
function returnQuote(data){

// data.quotes            = list of matching quotes
   // data.quotes[id].price  = price of quote
   // data.quotes[id].length = length of quote
   // data.quotes[id].text   = Any text/html you want.
   // data.text              = other text for display
   // data.error             = oops, problem
   if ( data.error ) {
      var html = "<p class=\"error\">We do not have a warranty for that item at that price.  Please try again.</p><!-- "+data.error+" //-->";
	 } else if ( !data.quotes ) {
      //var html = "<p class=\"quote\">"+data.text+"</p>";
			var html = "<p class=\"error\">We do not have a warranty for that item at that price.  Please try again.</p><!-- "+data.error+" //-->";
			var hide_button = true;
	 } else {
		 	var hide_button = null;
      var html = "";
      var quotes = data.quotes;
			var quote_id = null;
			var show_max = 6;
			var i=0;
			html += "<p class=\"quoteTitle\">Select a Warranty</p>";
			html += "<p>for your $"+data['item_price']+ " " +data['label']+"</p>";
			html += '<table id="QuoteResults" border="0" cellspacing="0" cellpadding="0">';
      for (var quote in quotes){
				if(i < show_max){
					//if(quotes[quote].adh!=1){
					 //html += "<h2 class=\"quoteTitle\">Your Quote</h2><p class=\"quote\">";
					 quote_id = quote;
					 /*
					 if (quotes[quote].length == 1) {
							html += "<h2 class=\"quoteTitle\">"+quotes[quote].length + " Year Warranty</h2>";
							html += "<p class=\"retail\">Retail: <span class=\"strikeout\">$"+quotes[quote].price+"</span></p>";
							html += "<p class=\"discount\">Discount: $"+quotes[quote].price+"</p>";
							html += "<p class=\"quote\">Price: <strong>$"+quotes[quote].price+"</strong></p>";
					 } else {
						*/
						/*
							html += "<h2 class=\"quoteTitle\">"+quotes[quote].length + " Year "+quotes[quote].type+" Warranty</h2>";
							html += "<p class=\"retail\">Everyday Low Price: <strong>$"+roundNumber(quotes[quote].price, 2)+"</strong></p>";
							html += "<p class=\"discount\">Discount: <strong>25%</strong> in additional savings</p>";
							var discount_p = roundNumber(quotes[quote].price - (quotes[quote].price * 0.25), 2);
							html += "<p class=\"quote\">Price: <strong>$"+discount_p+"</strong></p>";
						*/
					 //}
					 html += '<tr class="quote_res"><td class="quote_radio" align="left" valign="top">';
					 html += '<input type="radio" name="quote_id" value="'+quote+'" id="quote'+quote+'" />';
					 html += '</td><td class="quote_price" align="left" valign="top">';
					 var adh_text = (quotes[quote].adh==1) ? "<span class=\"with_adh\">with accidental damage from handling</span>" : "" ;
					 var q_price = CurrencyFormatted(roundNumber(quotes[quote].price, 2));
					 html += '<label class="quote_label" for="quote'+quote+'" ><span class="quote"><strong>$'+q_price+'</strong></span></label>';
					 html += '</td><td class="quote_details" align="left" valign="top"><label class="quote_label"><em>'+quotes[quote].length + ' Year '+quotes[quote].type+' Warranty '+adh_text+'</em></label>';
					 html += '</td></tr>';
					 html += '<tr class="heightone"><td><img src="'+site_root+'/public/images/spacer.gif" width="1" height="1"></td></tr>'
					//}
				}
				i++;
			}
			html += '</table>';
      html += "<!-- "+data.text+" //-->";
			jq('#EmailQuote').html('<a href="'+site_root+'sign_up/emailquote?cid='+data['device_id']+'&amp;price='+data['item_price']+'">Click here to email this quote.</a>');
   }
   //html += "<input type='button' id='reset' value='Reset'/>";
		
		jq("#retail").fadeOut("fast");
		jq("#other").hide().html(html).fadeIn("slow");
		jq("#ActionOptions").fadeIn("slow");
		//jq("#QuoteBox").height(250);
		jq("#QuoteBox").animate({ 
        height: 380
      }, 500 );
		//alert(jq("#QuoteBoxPad").css("background-image"));
		//jq("#QuoteBoxPad").css("padding-top","200");
		//jq('#quote_id').attr('value', quote_id);
		if (hide_button==true) {
			jq("#purchaseThisWarranty").fadeOut("fast");
		} else {
			jq("#purchaseThisWarranty").fadeIn("fast");
		}
		jq("#reset").click(function(){ 
			jq("#other").fadeOut("slow");
			jq('#ActionOptions').fadeOut('slow');
			jq("#retail").fadeIn("slow");
			//jq("#QuoteBox").height(170);
			jq("#QuoteBox").animate({ 
					height: 270
				}, 500 );
		});

}

/*
 * void categoryCallback(data)
 *
 * params: data is a javascript object that will replace the empty 'cats'
 *         object.
 *
 * This is the callback method that is returned after the page is loaded to
 * populate the initial category list.
 */
function categoryCallback(data){
   cats = data;
	 // alert(jq.toJSON(cats));
   // Empty the item select box
   jq("#item *").filter(function(){ 
         return (jq(this).html() != "Select Category");
   }).remove();

   // Refill the select box
   for ( var category in cats ){
      var html = "<option name='"+category+"' value='"+category+"'>"+cats[category].label+"</option>";
      jq(html).appendTo("#item");
   }
	 catsloaded = true;
}

/*
 * void retrieveCategories() makes the ajax call for the category data
 */
function retrieveCategories(){
    var data = { action: 'getCategories' };
//   jq.getJSON(url+"?action=getCategories", categoryCallback);
		// alert('cats follow: ');
		// alert(jq.toJSON(data));
   jq.post(url, data, categoryCallback ,"json");
}

/*
 * void submit()
 *
 * Submit button handler - checks form data and makes AJAX POST
 * call
 */
function submit(){
   // Get the category needed for the price quote
   var temp;
   var device = jq("#item option:selected").attr("name");
   if (temp = jq("#subitem option:selected").attr("name"))
      device = temp;

   // Get the price of the current product
   var price = jq("#price").val();
	 var promo_code = jq("#CouponCodeField").val();
	 
   // Check for values (add regexp for price quote here)
   if (!price || ! /^\$?(\d|,)*\.?\d{0,2}$/.test(price)){
      alert("Invalid price information, please fix.");
      return;
   }
   if (!device) {
      alert("Form is incomplete, please choose category");
      return;
   }

   // Construct POST values and send to server
   var data = { action:   "getQuote", 
      device_id: device,
      price:    price,
			promo_code: promo_code };
	 jq.post(url, data, returnQuote,"json");
	 jq('#device_id').attr('value', device);
	 jq('#purchase_price').attr('value', price);
}

/*
 * void changeItem()
 *
 * params:
 *
 * Called on select box change: Adds subcategories if needed
 */
function changeItem(){

   // jq(this) == item
   var currentCat = jq(":selected", this).attr('name');

   //   First check if the list exists and remove (+ the linebreak)
   //jq("#subitem").next().andSelf().remove();
	 jq("#SubItemBox").slideUp();
   jq("#subitem").remove();

   // if it has sub categories, add the subcategory list
   if (cats[currentCat] && cats[currentCat].devices){
      var devices = cats[currentCat].devices;
      var html = "<select id='subitem'>";
      for ( var subcat in cats[currentCat].devices ){
         html += "<option name='"+subcat+"' value='"+subcat+"'>"+devices[subcat].label+"</option>";
      }
      html += "</select>";
      //jq("label[for='item']").after(html);
			jq("#SubItemBox").append(html);
			jq("#SubItemBox").slideDown("slow");

   }
}

function startUp(){
   retrieveCategories();

   // Add on change handler for items
   jq("#item").change(changeItem);

   // Add button press handler for "get quote"
   jq("#getQuote").click(submit);
}

jq( function(){ startUp(); } );