//--------------------------------------------------------------------------------
//
//    General JavaScript file for the Mobile-For 4411 web application.
//  
//    author:			Gerrit Bertier (gerrit@marlon.be)
//                      Dieter Provoost (dieter@marlon.be)
//    copyright:		(c) 2010 - Marlon BVBA
//    since:			2010-01-20
//    last updated:		2010-05-06
//
//--------------------------------------------------------------------------------

//----------------------------------------
//  Fires when the DOM is ready.
//----------------------------------------
$(document).ready(function()
{
	// Initialize the web parking app
	webparkingapp.general.init();
});

//----------------------------------------
//  Web parking app functionality
//----------------------------------------
var webparkingapp =
{
    webparkingUrl: null,
    showConfirmation: false,
    translation: {},

	/**
	 * General web app functionality.
	 */
	general :
	{
		/**
		 * Initialize the web application.
		 */
		init : function()
		{
            if(!swfobject.hasFlashPlayerVersion('9.0.0'))
            {
                $('#map-app-container').hide();
                $('.flash_inavailable').show();
            }
            else
            {
                $('.flash_available').show();
            }

            // running sessions datagrid
            webparkingapp.webparkingUrl = $('#webparking-url').val();

			// Embed the flash file
			if($('.webparking').length > 0)
            {
                webparkingapp.flash.embedLoggedIn();
            }
            else
            {
                webparkingapp.flash.embedNormal();			
            }
			
			// Set html element(s) behaviour
			webparkingapp.general.setHTMLElementBehaviour();

            // tabs
            webparkingapp.general.tabs();

            // initial view
            if($('#webparking-licenseplate').html())
            {
                // show start session tab
                webparkingapp.general.showStartSessionTab();

                // prefill licenseplate field
                $('#licenseplate').val($('#webparking-licenseplate').html());
            }
            else
            {
                // datagrid users
                if($('#datagrid-running-sessions').length > 0) var dg = new datagrid('datagrid-running-sessions', webparkingapp.webparkingUrl + '/running-sessions', {'sortcolumn': 'time_start', 'sortdir': 'desc', 'page': 1} );
            }
		},
		
		/**
		 * Set the HTML element(s) behaviour.
		 */
		setHTMLElementBehaviour : function()
		{
			// City dropdown
			$('#cbo-city').change(function()
			{
				// Get selected value
				var selectedValue = $(this).val();
				
				// If selected value is not "0", then send to flash
				if (selectedValue != "0")
				{
					webparkingapp.flash.setCity(selectedValue);

                    // show start session "tab""
                    webparkingapp.general.showStartSessionTab();
				}
			});

            // change street
            $('#select_street').change(function()
            {
                // Get selected value
				var selectedValue = $(this).val();

				// If selected value is not "0", then send to flash
				if (selectedValue != "0")
				{
					webparkingapp.flash.setLocation(selectedValue, 'street');
				}
            });

            // change place
            $('#place_id').change(function(e)
            {
                // set zone to default element
                $('#zone_id').val(0);
            });

            // change zone
            $('#zone_id').change(function(e)
            {
                // set place to default element
                $('#place_id').val(0);
            });

            // start parking session
            $('#webparking-start-session').click(function(e)
            {
                // start session
                webparkingapp.general.startSession($(this));

                // prevent default behaviour
                e.preventDefault();
            });

            // stop session from parking session datagrid
            $('a.sessionaction_stop').live('click', function(e)
            {
                // confirmation sms
                var confirmationSms = $('#checkbox-' + $(this).classData('session')).attr('checked') ? 1 : 0;

                // stop session
                webparkingapp.general.stopSession($(this), confirmationSms);

                // prevent default behaviour
                e.preventDefault();
            });

            // start session from parking session datagrid
            $('a.sessionaction_start').live('click', function(e)
            {
                // scope
                var startSessionButton = $(this);

                // link already clicked?
                if(startSessionButton.classData('clicked') == 'yes') return;

                // disable
                startSessionButton.classData('clicked', 'yes');

                var parkingLocationId = $(this).classData('parkinglocation');
                var phoneId = $(this).classData('phone');
                var licensePlate = $(this).classData('licenseplate');
                var confirmationSms = $('#checkbox-' + $(this).classData('session')).attr('checked');

                webparkingapp.general.startSessionAjaxCall(parkingLocationId, phoneId, licensePlate, confirmationSms, function(){
                    startSessionButton.classData('clicked', 'no');
                });

                // prevent default behaviour
                e.preventDefault();
            });
		},

        startSession: function(startSessionButton)
        {
            var parkingLocationId = $('#place_id').val() != 0 ? $('#place_id').val() : $('#zone_id').val();
            var phoneId = $('#phone_id').val();
            var licensePlate = $('#licenseplate option:selected').text();
            var confirmationSms = $('#confirmation').attr('checked');

            // validation
            if(parkingLocationId == 0)
            {
                // add css error classes
                $('#advanced-search').addClass('error');

                // error messages
                $('#advanced-search dt').show();
                $('#advanced-search dd').show();

                return;
            }

            // disable button
            $(startSessionButton).attr('disabled', 'disabled');
            $('<img src="/custom/frontend/4411/0.0.1/img/ajax-loader.gif" alt="loading..."/>').insertAfter(startSessionButton);

            // clear errors
            $('#advanced-search').removeClass('error');
            $('#advanced-search .error').hide();

            webparkingapp.general.startSessionAjaxCall(parkingLocationId, phoneId, licensePlate, confirmationSms, function(){
                // enable button
                startSessionButton.attr('disabled', false);
                $('#submitbtn img').remove();
            });
        },

        startSessionAjaxCall: function(parkingLocationId, phoneId, licensePlate, confirmationSms, callback)
        {
            // clear confirmation messages
            webparkingapp.general.clearConfirmationMessages();

            // start session
            $.post(webparkingapp.webparkingUrl + '/start-session/', {'parkingLocationId': parkingLocationId, 'phoneId': phoneId, 'licensePlate': licensePlate, 'confirmationSms': confirmationSms ? 1 : 0}, function(data)
            {
                // json parsing
                data = $.evalJSON(data);

                if(data.status == 1) // session successfully started
                {
                    // show parking session confirmation message
                    $('#sessions-active .confirmation span').html(data.data);
                    $('#sessions-active .confirmation').show();
                    webparkingapp.showConfirmation = true;

                    // trigger click tab active parking sessions
                    $('#webparking-content #tabs li a:first').trigger('click');
                }
                else
                {
                    // show parking session error message
                    $('.confirmation-error span').html(data.data);
                    $('.confirmation-error').show();
                    webparkingapp.showConfirmation = false;
                }

                // execute callback
                callback();
            });
        },

        stopSession: function(stopSessionButton, confirmationSms)
        {
            // link already clicked?
            if(stopSessionButton.classData('clicked') == 'yes') return;

            // disable
            stopSessionButton.classData('clicked', 'yes');

            var parkingSessionId = stopSessionButton.classData('session');
            var phoneId = stopSessionButton.classData('phone');
            //var confirmationSms = stopSessionButton.classData('confirmation');

            webparkingapp.general.stopSessionAjaxCall(parkingSessionId, phoneId, confirmationSms, function() {webparkingapp.general.stopSessionCallback(stopSessionButton)});
        },

        stopSessionAjaxCall: function(parkingSessionId, phoneId, confirmationSms, callback)
        {
            // clear confirmation messages
            webparkingapp.general.clearConfirmationMessages();

            // start session
            $.post(webparkingapp.webparkingUrl + '/stop-session/', {'parkingSessionId': parkingSessionId, 'phoneId': phoneId, 'confirmationSms': confirmationSms}, function(data)
            {
                // json parsing
                data = $.evalJSON(data);

                if(data.status == 1) // session successfully stopped
                {
                    // show parking session confirmation message
                    $('#sessions-active .confirmation span').html(data.data);
                    $('#sessions-active .confirmation').show();

                    webparkingapp.showConfirmation = true;

                    // trigger click tab active parking sessions
                    $('#webparking-content #tabs li a:first').trigger('click');
                    
                    // execute callback on success
                    callback();
                }
                else
                {
                	$('#sessions-active .confirmation span').html(data.data);
                	$('#sessions-active .confirmation').show();
                }
            });
        },

        stopSessionCallback: function(stopSessionButton)
        {
            // enable button
            stopSessionButton.classData('clicked', 'no');
            stopSessionButton.children('span').html(webparkingapp.translation.btnStart);
        },

        tabs: function()
        {
            $('#webparking-content #tabs li a').each(function(i){
                $(this).click(function(e){

                    // hide advanced search tab
                    $('#advanced-search').hide();

                    // set other tabs as not selected
                    $('#webparking-content #tabs li').each(function(index, item){
                        $(item).removeClass('selected');
                    });

                    // set current tab as selected
                    $(this).parent('li').addClass('selected');

                    // hide all sections
                    $('#webparking-content .content-section').each(function(loop, item){
                        $(item).hide();
                    });

                    // clear confirmation messages
                    webparkingapp.general.clearConfirmationMessages();

                    // clear selected city
                    $('#cbo-city').val(0);

                    // tab name
                    tabName = this.href.split('#')[1];

                    // show selected section
                    $('#' + tabName).show();

                    // load dynamic data
                    switch($(this).classData('tab')[0])
                    {
                        case 'active':

                            $('#datagrid-running-sessions').html('<img src="/custom/frontend/4411/0.0.1/img/ajax-loader.gif" alt="loading..."/>');
                            var dg = new datagrid('datagrid-running-sessions', webparkingapp.webparkingUrl + '/running-sessions', {'sortcolumn': 'time_start', 'sortdir': 'desc', 'page': 1} );
                            break;

                        case 'recent':
                            $('#datagrid-recent-sessions').html('<img src="/custom/frontend/4411/0.0.1/img/ajax-loader.gif" alt="loading..."/>');
                            var dg2 = new datagrid('datagrid-recent-sessions', webparkingapp.webparkingUrl + '/recent-sessions', {'sortcolumn': 'time_start', 'sortdir': 'desc', 'page': 1} );
                            break;
                    }

                    // prevent default behaviour
                    e.preventDefault();
                });
            });
        },

        clearConfirmationMessages: function()
        {
            // hide confirmations
            if(!webparkingapp.showConfirmation)
            {
                $('#sessions-active .confirmation').hide();
                $('.confirmation-error').hide();
            }
            webparkingapp.showConfirmation = false; // render confirmations only once
        },

        showStartSessionTab: function()
        {
            // set other tabs as not selected
            $('#webparking-content #tabs li').each(function(index, item){
                $(item).removeClass('selected');
            });

            // hide all sections
            $('#webparking-content .content-section').each(function(loop, item){
                $(item).hide();
            });

            // show advanced search tab
            $('#advanced-search').show();

            // show selected section
            $('#start-session').show();
        }
	},
	
	/**
	 * Flash related functionality.
	 */
	flash :
	{
		/**
		 * Embed SWF file simulating an anonymous user.
		 */
		embedNormal : function()
		{
            var now = new Date();

			var flashvars = {
				contentswf: '/custom/frontend/4411/0.0.1/swf/webparking.swf?t=' + now.getTime(),
				langfile: '/custom/frontend/4411/0.0.1/swf/xml/be-nl.xml',
				fullheight: 'false'
			};

            // collect city specific data
            flashvars['amfgateway'] = $('#mapapp-flashvar-amfgateway').val();
            flashvars['countrylat'] = $('#mapapp-flashvar-countrylat').val();
            flashvars['countrylong'] = $('#mapapp-flashvar-countrylong').val();
            flashvars['cityid'] = $('#mapapp-flashvar-cityid').val();
            flashvars['countrycode'] = $('#mapapp-flashvar-countrycode').val();
            flashvars['apikey'] = $('#mapapp-flashvar-apikey').val();
            flashvars['locale'] = $('#mapapp-flashvar-locale').val();
            flashvars['showguidance'] = $('#mapapp-flashvar-showguidance').val();

			var params = {
                wmode: 'opaque'
            };
			var attributes = {
				id: 'map-app-container',
				name: 'map-app-container'
			};

			swfobject.embedSWF('/custom/frontend/4411/0.0.1/swf/webparking-wrapper.swf', 'map-app-container', '700', '360', '9.0.0','/custom/frontend/4411/0.0.1/swf/expressInstall.swf', flashvars, params, attributes);
		},
		
		/**
		 * Embed SWF file simulating a registered & logged in user.
		 */
		embedLoggedIn : function()
		{
			var flashvars = {
				contentswf: '/custom/frontend/4411/0.0.1/swf/webparking.swf',
				langfile: '/custom/frontend/4411/0.0.1/swf/xml/be-nl.xml'
			};

            // collect specific data
            flashvars['amfgateway'] = $('#mapapp-flashvar-amfgateway').val();
            flashvars['countrylat'] = $('#mapapp-flashvar-countrylat').val();
            flashvars['countrylong'] = $('#mapapp-flashvar-countrylong').val();
            flashvars['countrycode'] = $('#mapapp-flashvar-countrycode').val();
            flashvars['apikey'] = $('#mapapp-flashvar-apikey').val();
            flashvars['customerid'] = $('#mapapp-flashvar-customerid').val();
            flashvars['userapikey'] = $('#mapapp-flashvar-customerapikey').val();
            flashvars['cmsg'] = $('#mapapp-flashvar-cmsg').val();
            flashvars['locale'] = $('#mapapp-flashvar-locale').val();
            flashvars['car'] = $('#mapapp-flashvar-licenseplate').val();
            flashvars['phone'] = $('#mapapp-flashvar-phone').val();
            flashvars['showguidance'] = $('#mapapp-flashvar-showguidance').val();

			var params = {
                wmode: 'opaque'
            };
			var attributes = {
				id: 'map-app-container',
				name: 'map-app-container'
			};
			swfobject.embedSWF('/custom/frontend/4411/0.0.1/swf/webparking-wrapper.swf', 'map-app-container', '700', '360', '9.0.0', '/custom/frontend/4411/0.0.1/swf/expressInstall.swf', flashvars, params, attributes);
		},
		
		/**
		 * Set a city.
		 *
		 * @param cityID The ID of the city that was picked.
		 */
		setCity : function(cityID)
		{
            // set flash object city
            if(swfobject.hasFlashPlayerVersion('9.0.0')) document.getElementsByName('map-app-container')[0].setCity(cityID)

            /* PLACES */

            // remove erroring
            $('#advanced-search').removeClass('error');
            $('#advanced-search .error').hide();

            // clear dropdown except for the default element
            var defaultElementTextPlace = $('#place_id option[value="0"]').text();

            // clear dropdown
            $('#place_id').empty();

            // add first (default) element
            $('<option value="0">' + defaultElementTextPlace + '</option>').appendTo($('#place_id'));

            // disable places dropdown
            $('#place_id').attr('disabled', 'disabled');
            $('#place_id option[value="0"]').text('Bezig met laden...');

            // load place selector data
            $.get(webparkingapp.webparkingUrl + '/city-places/' + cityID, function(data){

                // parse JSON
                var places = $.evalJSON(data);

                if(places.length == 0)
                {
                    $('#place_id').parent('dd').hide();
                    $('#place_id').parent('dd').siblings('dt').slice(1,2).hide();
                    $('dt.no-arcgis').hide();
                    $('dt.arcgis').show();
                }
                else
                {
                    $('#place_id').parent('dd').show();
                    $('#place_id').parent('dd').siblings('dt').slice(1,2).show();
                    $('dt.arcgis').hide();
                    $('dt.no-arcgis').show();
                }

                // loop & add places
                $.each(places, function(i, item)
                {
                    // create element
                    var element = '<option value="' + i + '">' + item + '</option>';

                    // append element
                    $(element).appendTo($('#place_id'));
                });

                // enable places dropdown
                $('#place_id').attr('disabled', false);
                $('#place_id option[value="0"]').text(defaultElementTextPlace);
            });

            /* ZONES */


            // clear dropdown except for the default element
            var defaultElementTextZone = $('#zone_id option[value="0"]').text();

            // clear dropdown
            $('#zone_id').empty();

            // add first (default) element
            $('<option value="0">' + defaultElementTextZone + '</option>').appendTo($('#zone_id'));

            // disable zones dropdown
            $('#zone_id').attr('disabled', 'disabled');
            $('#zone_id option[value="0"]').text('Bezig met laden...');

            // load place selector data
            $.get(webparkingapp.webparkingUrl + '/city-zones/' + cityID, function(data){

                // parse JSON
                var zones = $.evalJSON(data);

                // loop & add places
                $.each(zones, function(i, item)
                {
                    // create element
                    var element = '<option value="' + i + '">' + item + '</option>';

                    // append element
                    $(element).appendTo($('#zone_id'));

                    // enable zones dropdown
                    $('#zone_id').attr('disabled', false);
                    $('#zone_id option[value="0"]').text(defaultElementTextZone);
                });
            });
            
		},
		
		/**
		 * Set a street.
		 *
		 * @param streetID The ID of the street that was picked.
		 */
		setLocation : function(locationID, zoomLevel)
		{
			if(document.getElementsByName('map-app-container').length > 0) document.getElementsByName('map-app-container')[0].setLocation(locationID, zoomLevel);
		},

        /**
        * A parking session has been started.
        */
        parkingSessionStarted : function(statusCode, message)
        {
            // clear confirmation messages
            webparkingapp.general.clearConfirmationMessages();

            if(statusCode == 1) // session successfully started
            {
                // show parking session confirmation message
                $('#sessions-active .confirmation span').html(message);
                $('#sessions-active .confirmation').show();
                webparkingapp.showConfirmation = true;

                // trigger click tab active parking sessions
                $('#webparking-content #tabs li a:first').trigger('click');
            }
            else // session could not be started
            {
                // do nothing
            }
        }
	}
}

