//## Application Object
function App(args) {
    this.view = args.view || "";
    this.path = args.path || "";
    this.page = args.page || "";
    this.file = args.file || "";
    this.logging = false;


    // log: log errors
    this.log = function(msg) {
        if(this.logging) {
            if(navigator.appName == 'Microsoft Internet Explorer') {
            //alert(msg);
            }
            else {console.log(msg);}
        }
    }

    // validateGame: Validate a game form
	this.validateGame = function () {
		this.log('app.validateGame');

		// Initialize
		var isValid = true;
        $("#err").hide();

        // Validate selects
        $("select[name^='q']").each(function() {
            if($(this).val() == undefined || $(this).val() == "") {
                isValid = false;
                $(this).addClass('err').prev('label').addClass('err');
                app.log('select: '+$(this).attr('name'));
            }
        });

        // Validate radios
        $("input[type='radio'][name^='q']").each(function() {
            var name = $(this).attr('name');
            if($("input[name='"+name+"']:checked").val() == undefined || $("input[name='"+name+"']:checked").val() == "") {
                isValid = false;
                $(this).parent().addClass('err');
                app.log('radio: '+name);
            }
        });

        // Validate sliders
        $("input[type='text'][name^='q']").each(function() {
            if(!$(this).isInt()) {
                isValid = false;
                $(this).addClass('err').parent().parent().find('div.slider').addClass('err');
                app.log('slider: '+$(this).attr('name'));
            }
        });

        // Valid form
        if(isValid) {return true;}
        
        // Errors
        else {
            $("#err h3").text('Please correct the errors in red').parent().show();
            if(app.view == 'fb'|| app.view == 'tab') {FB.Canvas.scrollTo(0,0);} else {$("html, body").animate({ scrollTop: 0 }, "slow");}
            return false;
        }
	}

    
    // Invite by Email
    this.inviteEmail = function (args) {
        this.log('app.inviteEmail');


        args['view'] = this.view; args['page'] = this.page; args['file'] = this.file;
        $.post(this.path+'/invite?_return=json', args);
        $("textarea[name='emails']").val("");
        _kmq.push(['record', 'Invite Email Sent', {'Page':this.file}]);
	    _gaq.push(['_trackPageview', this.path+'/invite-email/sent/'+this.file]);
        this.log(this.path+'/invite-email/sent/'+this.file);
        return false;
    }

    // Invite by Facebook
    this.inviteFacebook = function (args) {
		this.log('app.inviteFacebook');

        // See if league name and league id in form
        var message = "";
        if ('league_id' in args && 'league_name' in args) {
            message = "Join the "+args['league_name'];
            if(args['league_name'].toLowerCase().indexOf("league")) {message += ' League'}
        }
        else {message ='Do you want to play Premier League Predictions with me?' }


        FB.ui({
	            method: 'apprequests',
			    title: 'Who else loves the Premier League?',
                message: message
			    //data: this.file,
		    },
		    // Call back from facebook request dialog
		    function(data) {
                var request_ids = '';

                // Hide dialogs
                $('.fb_dialog_advanced').css('cssText', 'top: -10000px !important');

			    // Requests sent
			    if(data && 'request_ids' in data) {request_ids = data.request_ids.join(',')}

				// Call invite handler
				if(request_ids != '') {
                    args['sent_request_ids'] = request_ids
                    app.log(request_ids);

					// Post invites
                    args['view'] = app.view; args['page'] = app.page; args['file'] = app.file;
                    $.post(app.path+'/invite?_return=json', args);
					_kmq.push(['record', 'Invite Facebook Sent', {'view':app.view,'page':app.page, 'file':app.file}]);
					_gaq.push(['_trackPageview', app.path+'/invite-facebook/sent/'+app.file]);
                    app.log(app.path+'/invite-facebook/sent/'+app.file);
				}
			}
        );
        return false;
	}

    // Post comment
    this.postComment = function ($form) {
		this.log('app.postComment');
        // Get comment
        var comment = $form.find("textarea[name='comment']").val();
        comment = comment.replace(/(<([^>]+)>)/ig,"").replace(/\n\r?/g, '<br />'); // Strip tags and add line breaks
        if(comment == undefined || comment == "") {return false;}

        // Parent div
        var $parent = $form.closest('div.comment');

        // Make clone
        var $temp = $parent.prev('.template').clone().removeClass('template').addClass('temp');
        $temp.find('span.txt p:last').html(comment);
        $parent.prev('.template').before($temp.show());

        // Post comment
        $.post($form.attr("action")+'?_return=html', $form.serialize(), function(data) {
                // Remove clone and insert comment
                $temp.remove();
                $parent.prev('.template').before(data);
        });

        // Clear comment
        $form.find("textarea[name='comment']").val('');

        return false;
    }

}


