/* -*- mode: javascript; tab-width: 4; indent-tabs-mode: t; coding: utf-8 -*- */
/**
 * OrderPositionForm
 *
 * Ajax-Endpunkt für Artikel-Einkaufsformulare
 *
 * @package	Jescali Desk
 * @subpackage	mlm
 * @author      schaefer <sebastian@bergschaf.net>
 * @copyright   2010 Jescali concept GmbH (CH-020.4.031.966-8)
 * @version	SVN: $Id: OrderPositionForm.js 8786 2011-12-22 17:39:13Z schaefer $
 **/
var OrderPositionForm = {

	instance : null,

	domLoading : null,

	/**
	 * @type boolean
	 **/
	actionLocked : false,

	/**
	 * @type string
	 **/
	ajaxUrl : "/ajax/mlm/mlm_order_form.php",

	getInstance : function()
	{
		if(this.instance == null)
			this.init();

		return this.instance;
	},

	init : function()
	{
		this.domLoading = jQuery("<div/>")
						.attr('id', 'centeredLoadingContainer');

		var domLoadingOverlay = jQuery("<div/>")
						.attr('id', 'centeredLoadingOverlay')
						.addClass("centeredAjaxLoadingOverlay");

		var domLoadingAni = jQuery("<div/>")
						.attr('id', 'centeredLoading')
						.addClass("centeredAjaxLoading");

		this.domLoading.append(domLoadingOverlay)
					   .append(domLoadingAni)
					   .hide();

		jQuery("body").append(this.domLoading);

		OrderPositionForm.instance = this;

		return this;

	},

	/**
	 * @function _ajax
	 * @tparam string func
	 * @tparam object params
	 * @tparam function callFunc
	 **/
	_ajax : function(func, params, callFunc)
	{
		if(this.actionLocked && func != "refreshBasket")
		{
			return;
		}

		params['type'] 	= "json";
		params['function'] = func;

		OrderPositionForm._showLoading();
		jQuery.ajax({
			url: 	this.ajaxUrl + "?" + this._serialize(params),
			data: 	params,
			dataType: 'json',
			cache: false,
			contentType: "application/json",
			type:	'POST',
			success: function(d)
			{
				OrderPositionForm._hideLoading();
				callFunc(d);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown)
			{
				//var jsonResponse = eval("["+d.responseText+"]"); // @todo IE9 fehler!
				OrderPositionForm._hideLoading();
				//alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				//alert(jsonResponse[0].error, "error");
			},
			complete: function(d,st)
			{
				//alert("hmm");
				//alert(st);
			}
		});
	},

	_serialize : function(obj, prefix) {
                var str = [];
                for(var p in obj) {
                        var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
                        str.push(typeof v == "object" ?
                                InlineCashbox._serialize(v, k) :
                                encodeURIComponent(k) + "=" + encodeURIComponent(v));
                }
                return str.join("&");
        },


	/**
	 * @function _showLoading
	 **/
	_showLoading : function()
	{
		var inst = OrderPositionForm.getInstance();
		inst.domLoading.show();
		inst.actionLocked = true;
		//jQuery('.toolbar_loading').show();
	},

	/**
	 * @function _showLoading
	 **/
	_hideLoading : function()
	{
		var inst = OrderPositionForm.getInstance();
		inst.domLoading.hide();
		inst.actionLocked = false;
		//jQuery('.toolbar_loading').hide();
	},

	/**
	 * @function show
	 * @tparam int art_article_id
	 * @tparam string system_type
	 **/
	show : function(art_article_id, system_type)
	{
		if(typeof system_type == 'undefined')
			system_type = 'shop';


		var inst = OrderPositionForm.getInstance();

		inst._ajax("show", {id_art_article: art_article_id, system: system_type}, OrderPositionForm._show);
	},

	_show : function(data)
	{
		if(typeof data.order_form == 'undefined')
			return; // @todo fehlerbehandlung

		var form = data.order_form;
		jQuery('.art_order_form_container').remove();

		jQuery('body').append(form);
		var opener = data.opener_js;

		eval(opener);
	},

	/**
	 * @function show
	 * @tparam int art_article_id
	 * @tparam string system_type
	 **/
	submit : function(domForm, system_type)
	{
		if(typeof system_type == 'undefined')
			system_type = 'shop';

		jQuery('div.minimum_price_mismatch_row').hide();

		var minimumPrice = jQuery('#minimum_price_per_unit').val();
		var customPrice  = jQuery('#order_form_price_per_unit').val();

		if(typeof minimumPrice != 'undefined' && typeof customPrice != 'undefined')
		{
			customPrice  = customPrice.replace(/,/,".");
			minimumPrice = minimumPrice.replace(/,/,".");
			if(parseFloat(customPrice) < parseFloat(minimumPrice))
			{
				jQuery('div.minimum_price_mismatch_row').show();
				return;
			}
		}else if(typeof customPrice == 'undefined')
		{
			customPrice = 0;
		}

		if(system_type == 'shop')
		{
			var articleForm = jQuery('#add_article_to_cart');
			if(typeof articleForm == 'undefined')
			{
				alert('Could not find article form. Aborting.');
				return;
			}

			var pricePerUnitHidden = jQuery("<input type='hidden' name='order_form_price_per_unit' value='" + customPrice + "'/>");
			articleForm.append(pricePerUnitHidden);

			jQuery(".order_form_additional_var").each(function(n,e){
				articleForm.append(this);
			});

			articleForm.submit();
		}



		//var inst = OrderPositionForm.getInstance();

		//inst._ajax("submit", {id_art_article: art_article_id, system: system_type}, OrderPositionForm._show);
	},

	_submit : function(data)
	{
		if(typeof data.order_form == 'undefined')
			return; // @todo fehlerbehandlung

		var form = data.order_form;
		jQuery('.art_order_form_container').remove();

		jQuery('body').append(form);
		var opener = data.opener_js;

		eval(opener);
	}
};

