/**
 * General JavaScript file for the MobileFor 4411 website.
 *
 * @author 			Gerrit Bertier (gerrit@marlon.be)
 * @copyright		Marlon BVBA <http://www.marlon.be>
 * @date 			2009-09-10
 * @lastmodified	2009-12-09
 */

/**
 * Document Object Model (DOM) ready
 */
$(document).ready(function()
{
	// Initialize

	// Set JS classname on html tag
	$('html').removeClass('no-js').addClass('js');

	// Set user action buttons width
	home.setUALoginWidth();

	// Add 'span' elements to .rte li elements
	general.fixRTELists();

	// Set user action buttons behavior
	general.setUAButtonBehavior();

	// Set datepicker options & init them
	general.setDatepickers();

	// Fix layout issues
	layout.init();

	// Set form labels height
	general.setFormLabelsHeight();

	// Session overview: show/hide actions filter
	sessions.showHideActionsFilter();

	// Where to park? City dropdown
	where.init();

	// Init map if needed
	map.init();

    // Login
    login.init();

    // Register
    register.init();

	// Edit phone form
	editPhone.init();

    // list actions
    list.init();


	var ctr=0;
	// keep alive sessions
	$.PeriodicalUpdater('/pdu.php', {
	  minTimeout: 10*6000,
	  maxTimeout: 10*60*6000,
	  multiplier: 2.3,
		type: 'ajax',
		data: function() { return ctr++; },
	  cache:true
	},
	function(data) {
		$('#curtime').html(data.curtime);
	});

	// Listen for click on submit a tag
    $('a.submit').click(function(e) {
        
        $(this).closest('form').submit();

        e.preventDefault();
    });
});
/**
 * General functions.
 */
var general =
{
	/*
	 * Set the user action button behaviour.
	 */
	setUAButtonBehavior : function()
	{
		// Check if quick login button is present in user actions button list.
		if ($('#useractions a#quick-login').length > 0)
		{
			$('#useractions a#quick-login').click(function(e)
			{
				// Toggle selected class on li (link)
				$(this).parents('li:first').toggleClass('selected');

				// Slide open/close the login div
				$('#useractions div#login').slideToggle(100);

				// Prevent default behaviour
                e.preventDefault();
			});

			// Fake click when on homepage
			if (($('.homepage').length > 0) && ($('#useractions a#quick-login').length > 0))
			{
				$('#useractions a#quick-login').click();
			}
		}
	},

	/*
	 * Fix RTE lists by adding a span inside each li, so the numbers/bullets can be in another color.
	 */
	fixRTELists : function()
	{
		// Check if quick login button is present in user actions button list.
		if ($('.rte li').length > 0)
		{
            $('.rte li').each(function() {
                $(this).wrapInner('<span></span>');
            });

            /*
			// Loop over all ol's
			for (var i = 0; i < $('.rte li').length; i++)
			{
				// Wrap a span inside the li
				$('.rte li:eq(' + i + ')').wrapInner('<span></span>')
			}
            */
		}
	},

	/*
	 * Set datepicker options & initialize the date pickers (if any)
	 */
	setDatepickers : function()
	{
		if ($('.datepicker').length > 0)
		{
			$('.datepicker').datepicker(
			{
				showOtherMonths: true,
				firstDay: 1,
				dateFormat: 'dd/mm/yy',
				showOn: 'both',
				buttonImage: '/custom/frontend/4411/0.0.1/img/btn-calendar.png',
				buttonImageOnly: true,
				showAnim: 'slideDown'
			});

			//hover states on the static widgets
			$('#dialog_link, ul#icons li').hover(
				function() { $(this).addClass('ui-state-hover'); },
				function() { $(this).removeClass('ui-state-hover'); }
			);

			if ($('iframe.ui-datepicker-cover').length > 0)
			{
				$('iframe.ui-datepicker-cover').css('left', $('.ui-datepicker').position().left);
				$('iframe.ui-datepicker-cover').css('top', $('.ui-datepicker').position().top);
			}
		}
	},

	/*
	 * Set form labels height
	 */
	setFormLabelsHeight : function()
	{
		// Check if there are actually dt items
		if ($('form dl dt').length > 0)
		{
			// Loop over all labels
			$('form dl dt').each(function(i)
			{
				// Check if this dt is higher then 25 px (single line = 20 px)
				if ($(this).height() > 25)
				{
					// Target the dd and change it's top margin
					var heightDiff = $(this).height() - 20;
					$(this).next().css("padding-bottom", heightDiff + "px");
				}
			});
		}
	}
}

/**
 * General layout functions.
 */
var layout =
{
	/*
	 * Init
	 */
	init : function()
	{
		// Fix services short description & section-description height
		if ($('.services').length > 0)
		{
			layout.fixServicesShortDescriptionHeight();
		}

		if ($('.unregistered').length > 0)
		{
			layout.fixUnregistedContentAndSidebarHeight();
		}

		if ($('.city-map').length > 0)
		{
			layout.fixCityMapContentAndSidebarHeight();
		}
	},

	/*
	 * Fix services short description & section-description height
	 */
	fixServicesShortDescriptionHeight : function()
	{
		// Get heights
		var shortDescHeight = $('.services #short-description p').height();
		var sectionDescHeight = $('.services .section-description').height();

		// Set height (if needed)
		if (shortDescHeight > sectionDescHeight)
		{
			$('.services .section-description').height(shortDescHeight);
		}
	},

	/**
	 * Fix content & sidebar height
	 */
	fixUnregistedContentAndSidebarHeight : function()
	{
		// Get heights
		var contentHeight = $('#content').height();
		var sidebarHeight = $('.unregistered').height();

		// Sidebar is positioned 150px higher then content
		if (sidebarHeight - 150 > contentHeight)
		{
			$('#content').height(sidebarHeight - 150);
		}
	},

	/**
	 * Fix content & sidebar height
	 */
	fixCityMapContentAndSidebarHeight : function()
	{
		// Get heights
		var contentHeight = $('#content').height();
		var sidebarHeight = $('#aside').height();

		// Sidebar is positioned 150px higher then content
		if (sidebarHeight - 90 > contentHeight)
		{
			$('#content').height(sidebarHeight - 90);
		}
	}
}

/**
 * Homepage related functions.
 */
var home =
{
	/*
	 * Set the userinteractions div width when a login (not logged in) window is present (for IE positioning).
	 */
	setUALoginWidth : function()
	{
		// Check if user actions div is present
		if ($('#useractions').length > 0 && ($('#login').length > 0))
		{
			// Init max width
			var maxWidth = 1;

			// Get max width (buttons or blocks)
			maxWidth = $('#useractions ul').innerWidth();
			($('#useractions div.block').innerWidth() > maxWidth) ? maxWidth = $('#useractions div.block').innerWidth() : null;

			// Set width
			$('#useractions').css('width', maxWidth);
		}
	}
}

/**
 * Sessions overview related functions
 */
var sessions =
{
	/*
	 * Show or hide the parking actions filter according to the selected type filter.
	 */
	showHideActionsFilter : function()
	{
		if ($('input[name="chk-type"]').length > 0)
		{
			$('input[name="chk-type"]').change(function()
			{
				if ($('input[name="chk-type"]:checked').val() == "1")
				{
					$('#actions-filter').show();
				}
				else
				{
					$('#actions-filter').hide();
				}
			});
		}
	}
}

/**
 * Where to park? related functions
 */
var where =
{
    init: function()
    {
        $('#select_city').change(function(e) {
            if($(this).val() != 0)
            {
                // Get base
                var baseurl = $('#baseurl').val();

                // Redirect
                window.location = baseurl + $(this).val() + '#container';
            }
        });
    }
}

/**
 * Google maps app related functions
 */
var map =
{
	/*
	 * Initialize the map
	 */
	init : function()
	{
		if ($('#gmap').length > 0)
		{
			var gMapsDemo = new GMapsApp($('#gmap'), $('#map-inputs #map-content'), $('#map-controls'));
		}
	}
}

var register =
{
	init: function()
	{
		if ($('#sameaddress').length > 0)
		{
			$('#sameaddress').click(function(e)
			{
				register.toggleAddress($(this).is(':checked'));
			});

			// this.toggleAddress($('#sameaddress').is(':checked'))
		}
	},

    toggleAddress: function(state)
    {
        if(state)
        {
            // Copy textfields
            $('#billing_street').val($('#street').val())/*.attr('disabled', true)*/;
            $('#billing_city').val($('#city').val())/*.attr('disabled', true)*/;
            $('#billing_postal').val($('#postal').val())/*.attr('disabled', true)*/;
            $('#billing_country_id').val($('#country_id').val())/*.attr('disabled', true)*/;
        }
        else
        {
            // Clear textfields
            $('#billing_street').val('').attr('disabled', false);
            $('#billing_city').val('').attr('disabled', false);
            $('#billing_postal').val('').attr('disabled', false);
            $('#billing_country_id').val('').attr('disabled', false);
        }
    }
}

var login =
{
	init: function()
	{
		// Login form
		$('#btn-login').click(function(e) {

            e.preventDefault();

            // ajax call to login
            $.post($('#frm-login').attr('action'), {'username': $('#login #username').val(), 'password': $('#login #password').val(), 'remember': $('#remember').val()}, function(data){
                // Remove error messages
                $('#frm-login fieldset ul.errors').remove();

                // successful login?
                if(data[0] == 1)
                {
                    // reload page
                    window.location = data[1] ? data[1] : '/';
                }
                else
                {
                    // Remove previous errors
                    $('#frm-login fieldset ul.errors').remove();
                    $errors = $('<ul class="errors"></ul>').prependTo('#frm-login fieldset');

                    // display errors
                    if(data[1].notfound != '')
                    {
                        // General user not found error
                        $errors.append('<li>' + data[1].notfound + '</li>');
                    }
                    else
                    {
                        if(data[1].username != '')
                        {
                            $errors.append('<li>' + data[1].username + '</li>');
                        }
                        if(data[1].password != '')
                        {
                            $errors.append('<li>' + data[1].password + '</li>');
                        }
                    }

                }
            }, "json");

			return false;
		});

	}
}

/**
 * Edit phone nr. form
 */
var editPhone =
{
	/*
	 * Initialize the edit phone form (if present)
	 */
	init : function()
	{
       /*
		// Check if this is the correct form
		if ($('form #group_id').length > 0)
		{
			// Hide new group textfield
			$('form #group').parent().hide();

			// Dropdown change
			$('form #group_id').change(function()
			{
				// If the value linked to 'new group' has been selected, show the textfield
				if ($(this).find('option:selected').val() == '-')
				{
					// Show the field
					$('form #group').parent().show();
				}
				else
				{
					// Empty field
					$('form #group').val('');
					// Hide the field
					$('form #group').parent().hide();
				}
			});
		}*/
	}
}

var list = {
	init: function() {

		$('.list.deletable .ico-delete').live('click', function(event) {

            list.deleteItem(event, this.href);
			event.preventDefault();
		});

		$('.list .ico-remove-group').click(function(event) {
			list.deleteItem(event, this.href);
			event.preventDefault();
		});
	},

	/**
	 * Toggle delete warning in list
	 *
	 * @param {Object} event
	 * @param {String} type ('nav' or 'table');
	 */

	deleteItem: function(event, url) {
		// loading msg

		// fetch delete msg
		$.get(url, function(deleteMsg)
		{
			// Get the list (can be div (for #navigation) or table)
			$list = $(".list");

			// Get the type (table or div)
			var type = ($list.get(0).tagName).toLowerCase();
			var html;
			var detailRow;

			// Get TR
			$target = $(event.target);
			$parent = $target.parent().parent();
			$parent.hide();

			var rowHeight = 24;

		    // Create overlay to cancel action
			overlay = $('<div id="overlay"></div>');


            // Get number of columns
            numCols = $('.list tr:last').children().length;

            html = $('<tr class="delete-row"><td colspan="' + numCols + '">' + deleteMsg + '</td></tr>');

            zIndex = 50;

            // Insert delete HTML
            $(html).insertAfter($parent);

            // Hide subversions row (if available)
            if($('tr.detail-row', $parent.next().next()).length > 0) {
                $detailRow = $parent.next().next();
                $detailRow.hide();
            }

            $("#btn-cancel").click(function(event) {
                $(html).remove();
                $parent.show();
                $(overlay).remove();

                // Show detail row
                //$detailRow.show();

                event.preventDefault();
            });
            //$list.append(overlay);
            overlay.appendTo($list);

			// Position the overlay
			overlay.css({
			/*	width: (document.body.clientWidth) + 'px',
				height:( document.body.clientHeight) + 'px',
				left: -(overlay.offset().left) + 'px',
				top: -(overlay.offset().top) + 'px',*/
				'z-index': zIndex
				//background: '#f00'
			});
			// Click on overlay is same behavior as cancel button
			overlay.click(function(event) {
				$("#btn-cancel").trigger('click');
				$(this).remove();
			});

		});
	},

	/**
	 * Custum alternateRows function
	 * Can't make use of build-in jquery odd/even functionality
	 * -> function must be able to traverse nested tables
	 *
	 * @param {Object} target
	 */

	alternateRows: function(target) {
		// Set index
		var index = 0;

		$('tbody tr', target).each(function() {
			// Skip detail-row tr (wrapper around nested table)
			if (!$(this).hasClass('detail-row')) {
				if (index % 2 != 0)
					// even
					$(this).removeClass('odd').addClass('even');
				else
					// odd
					$(this).removeClass('even').addClass('odd');
				index++;
			}
		});
	}
}


