jQuery(function($) {

    // run the app
    var app = $.sammy(function() {
        var $form = $('#encoder'),
            $accordion = $('#accordion'),
            $indicator = $('#indicator'),
            $qr = $('#qr'),
            msg = '',
            $download = $('#downloader'),
            halt = false,
            $trackable = $('#trackable'),
            listId = 0,
            $report = $('#reporter'),
            $short = $('#shawty');

        $form.find('a.btn-create').click(function() {
            $form.submit();
            return false;
        });

        var pills1 = $('#phones .pill').click(function() {
            var $this = $(this);

            pills1.removeClass('selected');
            $this.addClass('selected');

            $('#phones div').hide();
            $($this.attr('href')).show();

            return false;
        });

        var pills2 = $('#phonesms .pill').click(function() {
            var $this = $(this);

            pills2.removeClass('selected');
            $this.addClass('selected');

            $('#phonesms div').hide();
            $($this.attr('href')).show();

            return false;
        });

        var pills3 = $('#card-fields .pill').click(function() {
            var $this = $(this);

            pills3.removeClass('selected');
            $this.addClass('selected');

            $('#card-fields div.ph').hide();
            $($this.attr('href')).show();

            return false;
        });

        $accordion.accordion({ fillSpace: true, change: function(e, ui) {
            window.location.hash = '#/create/' + ui.newHeader.attr('id');
        }
        });

        // enable date pickers
        var datepickoptions = { altFormat: 'yymmdd', dateFormat: 'DD, MM d, yy', showAnim: 'slide', showOptions: { direction: 'up'} }
        $('#input-event-start-date').datepicker($.extend(datepickoptions, { altField: '#input-event-start-date-raw' }));
        $('#input-event-end-date').datepicker($.extend(datepickoptions, { altField: '#input-event-end-date-raw' }));

        function renderQR() {
            var fg = $('#fg').val();
            if(fg != "" && fg.substring(0, 1) != "#") fg = "#" + fg;

            var inputs = $form.find(':input').attr('disabled', 'disabled');
            $indicator.show();
            $download.hide();
            $report.hide();
            $short.hide();
            $qr.hide().load(function() {

                if (halt) return;
                $indicator.animate({ opacity: 1 }, 2000, function() {
                    $(this).hide();
                    $qr.fadeIn('slow');
                    $download.find('a').attr('href', I1.AppRoot + "Home/Download/?resolution=300&msg=" + encodeURIComponent(msg) + "&color=" + encodeURIComponent( fg )).end().slideDown('slow');

                    if(listId > 0) {
                        $short.find('.url').html(msg).end().slideDown('slow');
                        $report.find('a').attr('href', I1.AppRoot + "List/Status/" + listId).end().slideDown('slow');
                        listId = 0;
                    }
                    
                    inputs.attr('disabled', '');
                });

            }).attr('src', I1.AppRoot + "qr.aspx?msg=" + encodeURIComponent(msg) + "&color=" + encodeURIComponent( fg ));
        }

        this.after(function() {
            if (this.verb != 'post') return;

            renderQR();
        });

        this.get('#/create/:id', function() {
            $form.attr('action', '#/create/' + this.params.id).find(':input:visible:enabled:first').focus();
            $accordion.accordion('activate', '#' + this.params.id);
        });

        this.post('#/create/url', function() {
            msg = $('#input-url').val();
            if (msg.indexOf('://') < 0) msg = 'http://' + msg;

            if (!$trackable.is(':checked')) return;

            halt = true;
            
            var trackParams = 'msg=' + encodeURIComponent(msg);
            var listName = $('#input-url-label').val();
            if(listName != '') trackParams += '&name=' + encodeURIComponent(listName);
            var tags = $('#input-url-tags').val();
            trackParams += '&tags=' + encodeURIComponent(tags);

            $.post(I1.AppRoot + 'List/Single', trackParams, function(data) {
                listId = data.listId;
                msg = I1.domainShort + data.codeId;

                halt = false;
                renderQR();
            }, "json");
        });

        this.post('#/create/email', function() {
            msg = $('#input-email').val();
        });

        this.post('#/create/phone', function() {
            msg = 'tel:' + (($('#phone-us').is(':visible'))
                            ? $('#input-phone-1').val() + $('#input-phone-2').val() + $('#input-phone-3').val()
                            : $('#input-phone-intl').val());
        });

        this.post('#/create/phonesms', function() {
            msg = 'sms:' + (($('#phonesms-us').is(':visible'))
                            ? $('#input-phonesms-1').val() + $('#input-phonesms-2').val() + $('#input-phonesms-3').val()
                            : $('#input-phonesms-intl').val());

            var txt = $('#input-phonesms-msg').val().substr(0, 160);
            msg += ':' + txt;
        });

        this.post('#/create/plain', function() {
            msg = $('#input-plain').val();
        });

        this.post('#/create/card', function() {
            var tel1 = (($('#contact-phone-us').is(':visible'))
                            ? $('#input-contact-phone-1').val() + $('#input-contact-phone-2').val() + $('#input-contact-phone-3').val()
                            : $('#input-contact-phone-intl').val());

            var tel2 = (($('#contact-phone2-us').is(':visible'))
                            ? $('#input-contact-phone2-1').val() + $('#input-contact-phone2-2').val() + $('#input-contact-phone2-3').val()
                            : $('#input-contact-phone2-intl').val());

            msg = 'MECARD:'
                + 'N:' + $('#input-contact-name').val() + ';'
                + 'TEL:' + tel1 + ';'
                + 'TEL:' + tel2 + ';'
                + 'EMAIL:' + $('#input-contact-email').val() + ';'
                + 'ADR:' + $('#input-contact-address').val() + ';'
                + 'ORG:' + $('#input-contact-company').val() + ';'
                + 'URL:' + $('#input-website').val() + ';'
                + ';';
        });

        this.post('#/create/event', function() {
            var begintime = $('#input-event-start-time-hh').val();
            if (begintime = '') begintime = 12;
            if ($('#input-event-start-time-ampm').val() == 'PM') begintime += 12;

            var endtime = $('#input-event-end-time-hh').val();
            if (endtime = '') endtime = 12;
            if ($('#input-event-end-time-ampm').val() == 'PM') endtime += 12;

            msg = 'BEGIN:VEVENT\n'
			    + ' SUMMARY:' + $('#input-event-title').val() + '\n'
			    + ' DTSTART:' + $('#input-event-start-date-raw').val() + 'T'
			    + begintime + $('#input-event-start-time-mm').val() + 'Z\n'
			    + ' DTEND:' + $('#input-event-end-date-raw').val() + 'T'
			    + endtime + $('#input-event-end-time-mm').val() + 'Z\n'
			    + ' END:VEVENT';
        });
    });

    app.run('#/create/url');

    $('#input-url').focus();

    picker('#fg');

});
