/**
 *  Pricing API
 */

/*
 * ReservationSpec:
 * {
 *  lang : en, de or hu (default hu) 
 * 	category : category id or acriss code (mandatory)
 *  tarifa : price table code
 * 	from : Parsable date format (mandatory)
 *  until : Parsable date format (mandatory)
 *  currency : "EUR" or "HUF" (mandatory)
 *  km_included : (optional, default 9999)
 * }
 * 
 * PricingInfo:
 * {
 *   status : "OK" if no error occured
 *   lang : en, de, or hu
 *   reservation : { title: "..", price: "..", currency: ".." }
 *   extras : [ { title: "..", price: "..", currency: ".." }, ... ]
 *   total :  { price: "..", currency: ".." },
 *   remarks: [ "..", ".."]
 *   
 *   msg : (optional, if error occured)
 * }
 * 
 * 
 */
if (!berauto)
	var berauto = {};
berauto.pricing = berauto.pricing || {}; 

berauto._text = { };
berauto._text.en = { 
		"TOTAL" : "Total",
		"FSTITLE" : "Price estimate"};
berauto._text.de = { 
		"TOTAL" : "Insgesamt",
		"FSTITLE" : "Kostenvoranschlag"};
berauto._text.hu = { 
		"TOTAL" : "Összesen",
		"FSTITLE" : "Bérlés költsége"};
berauto.text = berauto._text.hu;
berauto.lang = "hu";

berauto.setLang = function(lang) {
	berauto.text = berauto._text[lang] || berauto._text.hu;
	berauto.lang = lang;
};

berauto.pricing.grabSessionId = function() {
    var session_id_regex = /PHPSESSID=([a-z_0-9]+)/;
    if (session_id_regex.test(document.cookie) === true) {
        var result_arr = session_id_regex.exec(document.cookie);
        return result_arr[1];
    } else
        return false;
}

berauto.pricing.getPrice = function(reservationDetails, callback) {
	reservationDetails.tarifa = reservationDetails.tarifa || "R";
        
        var session_id = berauto.pricing.grabSessionId();
        if (session_id !== false) {
            reservationDetails.session_id = session_id;
        }
	$.getJSON("/api/pricing.json", 
			reservationDetails,
			callback); 
	/* For testing only */
	/*  callback({
    status : "OK",
    lang : "hu",
    reservation : { title: "CDMR R 28 days", price: "450.00", currency: "EUR" },
    extras : [ { title: "Airport transfer", price: "20.00", currency: "EUR" }, { title: "Sunday surcharge", price: "15.00", currency: "EUR" }  ],
    total :  { price: "485.00", currency: "EUR" }    
    }); */
	/*callback({"status" : "Error", "msg" : "Price engine offline"}); */
};


berauto.pricing.huf2ft = function(currency) {
	return (currency == "HUF") ? "Ft" : currency;
};

berauto.pricing.priceTableMarkup = function(rowMarkup) {
	return '<form action="" method="get"><fieldset><legend>'+berauto.text.FSTITLE+'</legend><table class="form">'
				+ rowMarkup
				+'</table></fieldset></form>';
};

berauto.pricing.genericRowMarkup = function(title,price,currency) {
	return '<tr class="priceLine"><td style="width:70%"><label>'+title+'</label></td><td><span>'
	     + price + ' ' + berauto.pricing.huf2ft(currency) + '</span></td></tr>';
};

berauto.pricing.totalRowMarkup = function(price, currency) {
	return '<tr class="priceLine"><td><label style="font-size:1.4em">'+berauto.text.TOTAL+'</label></td><td><span style="font-weight:bold;font-size:1.4em;color:yellow">'
           + price + ' ' + berauto.pricing.huf2ft(currency) + '</span></td></tr>';
};

berauto.pricing.errorRowMarkup = function(errMsg) {
	return '<tr class="priceLine"><td colspan="2"><label style="color:red">'+errMsg+'</label></td></tr>';
};

berauto.pricing.remarkRowMarkup = function(remarkMsg) {
	return '<tr class="priceLine"><td colspan="2"><label style="color:white">'+remarkMsg+'</label></td></tr>';
};

berauto.pricing.renderInProgressPriceTable = function($container) {
	$($container).html(
			berauto.pricing.priceTableMarkup(
					"<tr><td colspan='2'><img src='/images/ajax-loader.gif' /></td></tr>"));
};
berauto.pricing.resetPriceTable = function($container) {
	$container.html("");
};


berauto.pricing.renderPriceTable = function(pricingInfo, $container)
{
	var bp = berauto.pricing;
	
	if (pricingInfo.status && ("OK" == pricingInfo.status)) {
		var pi = pricingInfo;
		var rowMarkup = bp.genericRowMarkup(pi.reservation.title, pi.reservation.price, pi.reservation.currency);
		if (pi['extras']) { 
			$.each(pi.extras, function(idx,extra) { 
				rowMarkup += bp.genericRowMarkup(extra.title, extra.price, extra.currency); });
		}
		rowMarkup += bp.totalRowMarkup(pi.total.price, pi.total.currency);
                
                if (pi['remarks']) {
                        $.each(pi.remarks, function(idx,remark) {
                                rowMarkup += bp.remarkRowMarkup(remark);
                                });
                }
		
		$($container).html(bp.priceTableMarkup(rowMarkup));
	}
	else {
		$($container).html(
				bp.priceTableMarkup(
						bp.errorRowMarkup(pricingInfo.msg)));
	}
};

berauto.pricing.makeReservationDetails=function() {
	var from_date = new Date($("#from_date").datepicker( "getDate" ));
	var from = "";
	if (from_date && $("#from_date").val()) {
		var fyear = from_date.getFullYear();
		var fmonth = from_date.getMonth() + 1; /* 0-11 */
		var fday = from_date.getDate(); /* 1-31 */
		var fhour = $("#from_time_hour").val();
		var fmin = $("#from_time_min").val();	
		from = fyear+'-'+fmonth+'-'+fday+' '+(fhour || '00')+':'+(fmin || '00') +':00';
	}
		
	var to_date = new Date($("#to_date").datepicker( "getDate" ));
	var until = "";
	if (to_date && $("#to_date").val()) {
		var uyear = to_date.getFullYear();
		var umonth = to_date.getMonth() + 1; /* 0-11 */
		var uday = to_date.getDate(); /* 1-31 */
		var uhour = $("#to_time_hour").val();
		var umin = $("#to_time_min").val();
	    until = uyear+'-'+umonth+'-'+uday+' '+(uhour || '00')+':'+(umin || '00')+':00';
	}
	var currency = (berauto.lang == "hu" ? "HUF" : "EUR");
	var km_included =  $("#km_included option:selected").val();
	return {
		lang : berauto.lang,
		currency : currency,
		from : from,
		until : until,
		category : $("#vehicle_category").val(),
		km_included : km_included,
		pickup_location_code : $("#pickup_location_code").val(),
		dropoff_location_code : $("#dropoff_location_code").val() };
};

berauto.pricing.calculatePrice = function($priceTabCnt) {
                berauto.pricing.renderInProgressPriceTable($priceTabCnt);
		berauto.pricing.getPrice(berauto.pricing.makeReservationDetails(),function(data) { 
			berauto.pricing.renderPriceTable(data, $priceTabCnt);
                        // notify listeners
                        $(document).trigger("pricing:ready", data);

                    });
		return false;
};

berauto.pricing.ifAvailableCalculatePrice = function($priceTabCnt) {
    var selectorArr = [ "#from_date", "#to_date", "#km_included", "#vehicle_category",
                        "#pickup_location_code","#dropoff_location_code" ];
    var available = true;
    $.each(selectorArr, function(idx, elem) {
        if (!available)
           return false;
        var trimmed = $(elem).val().trim();
        available = available && (trimmed != "");
        });
    if (available) {
        return berauto.pricing.calculatePrice($priceTabCnt);
    } else {
        return false;
    }
};

berauto.pricing.onClickCalculatePrice = function($triggerElement, $priceTabCnt) {
	$triggerElement.click(function () {
            return berauto.pricing.ifAvailableCalculatePrice($priceTabCnt);
	});
};

berauto.pricing.ifInputChangesResetPriceTable = function($priceTabCnt) {
$("#from_date,#to_date,#km_included,#vehicle_category,#pickup_location_code,#dropoff_location_code").change(function() {
	berauto.pricing.resetPriceTable($priceTabCnt);
});        
};

berauto.pricing.ifInputChangesRecalculatePriceTable = function($priceTabCnt) {
$("#from_date,#to_date,#km_included,#vehicle_category,#pickup_location_code,#dropoff_location_code").change(function() {
	berauto.pricing.ifAvailableCalculatePrice($priceTabCnt);
});        
};


