/**
* Pension Danmark order form scripting
* @requires jQuery.ui.dialog
*/

var pd = pd || {};
pd.order = (function() {
    //	config
    var contSelector = '.order-list';

    //	private vars
    var $cont,
		summary;

    var init = function() {
        $cont = $(contSelector);
        if ($cont.length < 1) return;


        $(window).load(function() {
            //  open first orderlist
            $('.foldy')
            //	select only foldys containing a product list...
				.filter(function() {
				    return $(this).find(contSelector).length > 0;
				})
            //	...find links and trigger click to open first
				.find('.foldy-down a')
					.eq(0)
					.trigger('click');
        });

        //	reset link after input field
        $cont.find('li fieldset a').live('click', reset)
        $cont.find('li input:text')
        //	digit-only validation on input
			.each(digits)
			.live('keyup', digits)
        //	toggling normal postback
			.focus(function() {
			    preventPostback(confirm);
			})
			.blur(allowPostback);
        //	global submit
        $cont.find('input:submit').click(confirm);
    };

    /**
    * Replace standard submit (postback) of aspnet form with custom callback function to be called after validation
    * @param {Object} cb	function to call when submit is triggered
    */
    var preventPostback = function(cb) {
        if (typeof cb != 'function') return;
        $("#aspnetForm")[0].callback = cb;
    }

    /**
    * Set callback on aspnet form to false, allowing standard submit() to do postback
    */
    var allowPostback = function() {
        $("#aspnetForm")[0].callback = false;
    }

    /**
    * Validation for amount inputs, only allowing for numbers and showing reset button when valid number is entered
    */
    var digits = function() {
        if ($(this).val().match(/(\d{1,})/)) {
            var num = $(this).val().match(/(\d{1,})/)[0];
            $(this).val(num);
            $(this).next('a').css({ visibility: 'visible' });
        } else {
            $(this).val('');
            $(this).next('a').css({ visibility: 'hidden' });
        }
    };

    /**
    * Simple reset function for each amount input field
    * @param {Object} e	event object
    */
    var reset = function(e) {
        e.preventDefault();
        $(this)
			.css({ visibility: 'hidden' })
			.prev('input')
				.val('');
    };

    /**
    * Gather products where amount > 0 is entered by user, define lightbox contents
    * @param {Object} e 	event object
    */
    var confirm = function(e) {
        e && e.preventDefault();

        //	assemble order list
        var $list = $('<div class="order-list"><ul /></div>');
        $cont.find('input:text[value]').each(function() {
            var $li = $(this).closest('li').clone();
            $li.find('img, p, a.pdf').remove();
            $list.find('ul').append($li);
        });

        //	check order list length
        if ($list.find('li').length > 0) {
            $cont.find('input').addClass('ignore');

            summary = $('#order-material-summary');

            //	insert order list
            summary.find('.order-material-summary-descriptions').html($list);

            //	hide/show alternate content based on select
            summary.find('.alternate-control')
				.change(function() {
				    $el = $(this);
				    var v = $el.closest(':input').val();
				    $el.find('option').each(function() {
				        var id = $(this).attr('rel');
				        if ($(this).attr('selected')) $('#' + id).show();
				        else $('#' + id).hide();
				    });
				})
				.trigger('change');

            //	setup dialog if not inited
            if (summary.closest('.ui-dialog').length < 1) {
                //	complete shadow
                summary.after('<div class="shadow-bottom"/>');
                //	wrap in form for normal form behavior (enter = submit, etc)
                summary.find('fieldset').wrap('<form>');
                //	validate & submit
                summary.find('form')
					.submit(function(e) {
					    e.preventDefault();
					    if ($(this).valid()) post();
					});
                //	configure dialog
                summary.dialog({
                    autoOpen: false,
                    close: function() {
                        $cont.find('input').removeClass('ignore');
                    }
                });
            }

            summary.dialog('open');

        } else {
            //	highlight empty fields, show error
            $cont
				.find('input:text')
					.addClass('error')
					.keydown(function() {
					    $cont
							.find('input:text')
								.removeClass('error')
								.unbind('focus')
							.end()
							.find('.error-atleastone')
								.hide();
					})
					.end()
					.find('.error-atleastone')
						.show();
        }
    };

    var post = function() {
        var items = [], 			//	store ordered items
			data = new Object(); //	post data

        //	gather order items
        summary.find('.order-list li').each(function() {
            $li = $(this);
            if (!!$li.find('input').val()) items.push({
                amount: $li.find('input').val(),
                name: $li.find('h5').text()
            });
        });
        //	collect contact data
        summary.find('dl :input:not(:submit)').each(function() {
            data[this.name] = $(this).val();
        });
        data['items'] = items;

        $.ajax({
            url: '/Custom/Main/ComposerFunctions/OrderMaterial/OrderMaterialService.svc/Order',
            data: JSON2.stringify({ orderInfo: data }),
            dataType: 'json',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            success: function(resp) {
                feedback(resp.d);
            },
            error: function() {
                feedback(false);
            }
        });
    };

    /**
    * Based on true or false response from ajax call, a div with appropriate feedback is chosen for lightbox content
    * also reset all inputs on successful submit
    * @param {String} resp
    */
    var feedback = function(resp) {
        summary.dialog('close');
        var div = (resp == true) ? $('#order-material-success') : $('#order-material-failed');

        div.dialog({
            //	override default fadeIn animation since dialog is already present
            open: function() { }
        });

        div
			.find('input:eq(0)')
				.click(function() {
				    div.dialog('close')
				})
				.focus();
        //if (resp == true) $cont.find('li fieldset a').trigger('click');
    }

    return {
        init: init
    }
})();

$(document).ready(pd.order.init);
