// Read a page's GET URL variables and return them as an associative array.
function get_url_vars(){var vars = [], hash;    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    for(var i = 0; i < hashes.length; i++)    {        hash = hashes[i].split('=');        vars.push(hash[0]);        vars[hash[0]] = hash[1];    }    return vars;}
// Get specific get val
function get_var(name) { var vars = get_url_vars(); return vars[name]; }

function facebook_display_user_info(name, pic_url, profile_url, logout) {
    $('#fb_profile_info').html("<p>Logged in through facebook.com as <a href='" + profile_url + "'>" + name + "</a> (<a href='performance.aspx?pid=" + get_var('pid') + "' onclick='" + logout + "'>logout</a>)</p>");
    $("input#name").val(name);
    //FB.XFBML.Host.parseDomTree();
}

function facebook_get_permissions(fb_uid) {
    var permissions = FB.Facebook.apiClient.fql_query(
        'SELECT publish_stream FROM permissions WHERE uid=' + fb_uid,
        function(results) {
            if (!results[0].publish_stream) {
                FB.Connect.showPermissionDialog("publish_stream", function(perms) {
                    if (!perms) {
                        $('#fb_profile_info').hide();
                    } else {
                        $("#commentForm").show();
                    }
                });
            }
            else {
                $("#commentForm").show();
            }
        }
    );   
}

function facebook_get_user_info() {
    //get the users data from FB
    var fb_uid = FB.Facebook.apiClient.get_session().uid;
    var viewer = FB.Facebook.apiClient.fql_query(
        'SELECT name, pic_square_with_logo,profile_url FROM user WHERE uid=' + fb_uid,
        function(results) {
            facebook_display_user_info(results[0].name, results[0].pic_square_with_logo, results[0].profile_url, 'FB.Connect.logoutAndRedirect("performance.aspx?pid=' + get_var('pid') + '");return false;');
            facebook_get_permissions(fb_uid);
        }
    );   
}

function facebook_add_comment() {
    var production_id = get_var('pid');
    var title = $("input#production_title").val() + " at Wharton Center " + $("input#production_date_span").val() + ".";
    var href = "http://whartoncenter.com/boxoffice/performance.aspx?pid=" + production_id;
    var rating = $('#rating').val();
    var caption = "{*actor*} commented on on the show:";
    var description = $("textarea#comment").val();
    if (rating > 0) {
        if (description.length > 1) {
            caption = "{*actor*} rated the show " + rating + " stars:";
        }
        else {
            caption = "{*actor*} rated the show " + rating + " stars.";
        }
    }

    var buy_tickets = $("#ticket_link").val();
    var action_links = null;

    // check for ticket links that contain NA
    if (!buy_tickets.indexOf("NA") == 0) {
        action_links = [{ "text": "Buy tickets", "href": buy_tickets}];
    }

    if (description.length > 1) {
        description = '"' + description + '"';
    } else {
        description = null;
    }

    //var img_src = 'http://c0586342.cdn.cloudfiles.rackspacecloud.com/p' + production_id + '.jpg';
    var img_src = 'http://whartoncenter.com/images/social_networks/facebook/p' + production_id + '.jpg';
    var img_href = 'http://whartoncenter.com/boxoffice/performance.aspx?pid=' + production_id;

    var attachment = {
        'name': title,
        'href': href,
        'caption': caption,
        'description': description,
        'media': [{ 'type': 'image', 'src': img_src, 'href': img_href}]
    };

    FB.Connect.streamPublish(
        '',
        attachment,
        action_links,
        null,
        '',
        function (post_id, exception) {
            if (post_id) {
                $("#commentForm").submit();
            } else {
                //$("#commentForm").hide();
                $("#fb_profile_status_update").remove();
                $("#fb_profile_info").append("<p class='status_error'>There was an error posting the comment to facebook.com.  Please try again later.</p>");
            }
        },
        true
    );

    $("#fb_profile_info").append("<p class='status_update' id='fb_profile_status_update'>Saving...</p>");
}

$(function () {
    FB.init("d098c8195c13d9b03b31d3306e51f832", "xd_receiver.htm", { "ifUserConnected": facebook_get_user_info });

    $("#commentForm").hide().submit(function () {
        if (this.facebook_comment_submitted_flag == null) {
            this.facebook_comment_submitted_flag = true;
            facebook_add_comment();
            return false;
        }
        else {
            return true;
        }
    });

    // Remove the select list, insert hidden ratings field, and create the starRating div.
    $("select#rating").remove();
    $("label[for=rating]").after("<input type=\"hidden\" id=\"rating\" name=\"rating\" value=\"0\" \/>"); // added default of 0
    $("label[for=rating]").after("<div id=\"starRating\"><img alt=\" \" src=\"../images/comments/transparent.gif\" height=\"16\" width=\"80\" ismap=\"ismap\" usemap=\"#starRatingMap\" \/><\/div>");

    // Rating hover functions
    $("#rating1").hover(
		function () {
		    $("#starRating").addClass("one");
		},
		function () {
		    $("#starRating").removeClass("one");
		}
	);
    $("#rating2").hover(
		function () {
		    $("#starRating").addClass("two");
		},
		function () {
		    $("#starRating").removeClass("two");
		}
	);
    $("#rating3").hover(
		function () {
		    $("#starRating").addClass("three");
		},
		function () {
		    $("#starRating").removeClass("three");
		}
	);
    $("#rating4").hover(
		function () {
		    $("#starRating").addClass("four");
		},
		function () {
		    $("#starRating").removeClass("four");
		}
	);
    $("#rating5").hover(
		function () {
		    $("#starRating").addClass("five");
		},
		function () {
		    $("#starRating").removeClass("five");
		}
	);

    // Select ratings
    $("#rating1").click(
		function () {
		    $("#starRating").removeAttr("class");
		    $("#starRating").addClass("oneSelected");
		    $("#rating").val("1");
		}
	);
    $("#rating2").click(
		function () {
		    $("#starRating").removeAttr("class");
		    $("#starRating").addClass("twoSelected");
		    $("#rating").val("2");
		}
	);
    $("#rating3").click(
		function () {
		    $("#starRating").removeAttr("class");
		    $("#starRating").addClass("threeSelected");
		    $("#rating").val("3");
		}
	);
    $("#rating4").click(
		function () {
		    $("#starRating").removeAttr("class");
		    $("#starRating").addClass("fourSelected");
		    $("#rating").val("4");
		}
	);
    $("#rating5").click(
		function () {
		    $("#starRating").removeAttr("class");
		    $("#starRating").addClass("fiveSelected");
		    $("#rating").val("5");
		}
	);

});


