// Functions to fire on document.ready
$(document).ready(function(){
	// Navigation positioning - MUST BE BEFORE superfish()
	navPosition();

	// Superfish Navigation - this needs to fire ASAP to avoid an ugly delay
	superfish();
	if ($("#wxalerts li").length > 1) { wxalertCarousel(); }
    
    if ($('#skybox_carousel').length) { skyboxCarousel(); }
    
    if ($('#poster').length) { posterCarousel(); }
    
    // Font resize tool on story_detail.html.  Pass the name of the cookie
	fontResize("story_font_size");
	
    //dropCap("#article_body > p:first");

	// Initiate all tabs for jQuery's tab switching, and appTap tracking
	//var tabWrappers = $(".tab_wrapper > ul"); // Every tab container on the page
	var tabWrappers = $(".tab_wrapper"); // Every tab container on the page
	//var allTabs = tabWrappers.find("li"); // Every tab on the page
	tabWrappers.tabs();
    
	if ($('.popmenu_button').length) {
        $('.popmenu_button').popmenu({
            activeClass: "active"
        });
    }
	initContentRatings($('input[type=radio].rating-star'), $('form.rating_form')); // Initiate jQuery star-rating plugin for all input type=radio with class of rating-star
	initCellarBD();
	initAsphaltAppTap(); // Make sure this is called last
});

/*****************
 FUNCTIONS
*****************/
function superfish() {
    // Class name to be applied to active nav.  Used in superfish() init
    var path = 'current';
    
    // Parse the class chain on #site_nav and match "nav_xxxx" where "xxxx" is the section name (e.g. news, sports, business)
    var current_nav = $('ul#site_nav').attr('class').match(/nav_[a-z]*/); // match() returns an array
    
    // If the value for the current nav is "nav_" or null (i.e. something broke) then default to nav_news
    if (current_nav == null || current_nav[0] == 'nav_') {
        $('ul#site_nav li#nav_news').addClass(path);
    }
    else {
        $('ul#site_nav li#' + current_nav[0]).addClass(path);
        $('ul#site_nav li#' + current_nav[0] + ' > ul.secondary_nav').css('display', 'block'); // Works around an IE7 bug
    }

    // Initialize superfish
	$('ul#site_nav').superfish({ 
		pathClass: path,
		hoverClass: 'hover',
		pathLevels: 2,
		delay: 1500,
		speed: 'fastest',
		autoArrows: true,
		dropShadows: false
	});
}
function wxalertCarousel() {
    function wxalert_init(carousel) {
        var controls = "<div id='wxalert_controls'><a href='#alert_body' class='carousel_control carousel_prev'>Previous</a><a href='#alert_body' class='carousel_control carousel_next'>Next</a></div>";

        //controls_list.after(controls);
		$('#alert_body').prepend(controls);
		
        // Disable autoscrolling if the user clicks the prev or next button.
    	$('#wxalert_controls a.carousel_prev').bind('click', function() {
    		carousel.prev();
    		carousel.startAuto(0);
    		return false;
    	});

    	$('#wxalert_controls a.carousel_next').bind('click', function() {
    		carousel.next();
    		carousel.startAuto(0);
    		return false;
    	});

        // Pause autoscrolling if the user moves with the cursor over the clip.
    	carousel.clip.hover(function() {
    		carousel.stopAuto();
    	}, function() {
    		carousel.startAuto();
    	});
    }

    function onSlide(carousel, item, current_page, state) {
        $('#wx_controls li a').each(function() {
            if ($(this).attr('id') == 'page' + current_page) {
                $(this).parent().addClass('current');
            }
            else {
                $(this).parent().removeClass('current');
            }
        });
    }

    $('#wxalerts').jcarousel({
		auto: 8,
		animation: 250,
		easing: 'linear',
		scroll: 1,
		wrap: 'both',
		initCallback: wxalert_init,
		itemFirstInCallback: onSlide,
		buttonNextHTML: null,
		buttonPrevHTML: null
	});
}
function skyboxCarousel() {
    function carouselInit(carousel) {
        
        var pages = $('#skybox_carousel').children().size(); // Number of pages (displays max of 3 skyboxes per page)
        
        // Create "next" and "previous" controls
        var controls_list = $('#skybox_controls ul'); // Find this element once and reuse it below to cut down on DOM searching
        var controls = "<a href='#skybox_carousel' class='carousel_control carousel_prev' title='See previous group of skyboxes'>Previous</a><a href='#skybox_carousel' class='carousel_control carousel_next' title='See next group of skyboxes'>Next</a>";
        controls_list.after(controls);
        
        // Create pagination controls
        for(i=1; i <= pages; i++) {
            controls_list.append("<li><a href='#skybox_wrapper' id='page" + i + "' title='Jump to Skybox page " + i + "'>" + i + "</a></li>");
        }
        
        // Set first page indicator to current
        $('#skybox_controls ul li:first-child').addClass('current');
        
        // Bind click function to pagination controls
        $('#skybox_controls li').bind('click', function() {
            carousel.scroll($.jcarousel.intval($(this).text()));
            $('#skybox_controls li').each(function() {
                if ($(this).hasClass('current')) {
                    $(this).removeClass('current');
                }
            });
            $(this).toggleClass('current');
            return false;
        });
        
        // Bind click function to "next" button
        $('#skybox_controls .carousel_next').bind('click', function() {
            carousel.next();
			execAppTapEvent(this, "Event64", false);
            return false;
        });

        // Bind click function to "previous" button
        $('#skybox_controls .carousel_prev').bind('click', function() {
            carousel.prev();
			execAppTapEvent(this, "Event64", false);
            return false;
        });
    }
    
    function onSlide(carousel, item, current_page, state) {
        $('#skybox_controls ul li a').each(function() {
            if ($(this).attr('id') == 'page' + current_page) {
                $(this).parent().addClass('current');
            }
            else {
                $(this).parent().removeClass('current');
            }
        });
    }
    
    $('#skybox_carousel').jcarousel({
        initCallback: carouselInit,
        scroll: 1,
        wrap: "both",
        buttonNextHTML: null,
        buttonPrevHTML: null,
        itemFirstInCallback: onSlide
    });
}

function posterCarousel() {
    function poster_init(carousel) {	
    	var pages = $('#poster').children().size(); // Number of pages
    
        // Create "next" and "previous" controls
        var controls_list = $('#poster_controls ul'); // Find this element once and reuse it below to cut down on DOM searching
        var controls = "<a href='#poster' class='carousel_control carousel_prev' title='See previous poster content'>Previous</a><a href='#poster' class='carousel_control carousel_next' title='See next poster content'>Next</a>";

        controls_list.after(controls);
    
        // Create pagination controls
        for(i=1; i <= pages; i++) {
            controls_list.append("<li><a href='#poster' id='page" + i + "' + title='See poster page: " + i + "'>" + i + "</a></li>");
        }
    
        // Set first page indicator to current
        $('#poster_controls ul li:first-child').addClass('current');
    
        // Bind click function to pagination controls
        $('#poster_controls li').bind('click', function() {
            carousel.scroll($.jcarousel.intval($(this).text()));
            $('#poster_controls li').each(function() {
                if ($(this).hasClass('current')) {
                    $(this).removeClass('current');
                }
            });
            $(this).toggleClass('current');
    		carousel.startAuto(0);
            return false;
        });

        // Disable autoscrolling if the user clicks the prev or next button.
    	$('#poster_controls a.carousel_prev').bind('click', function() {
    		carousel.prev();
    		carousel.startAuto(0);
			execAppTapEvent(this, "Event65", false);
    		return false;
    	});

    	$('#poster_controls a.carousel_next').bind('click', function() {
    		carousel.next();
    		carousel.startAuto(0);
			execAppTapEvent(this, "Event65", false);
    		return false;
    	});

        // Pause autoscrolling if the user moves with the cursor over the clip.
    	carousel.clip.hover(function() {
    		carousel.stopAuto();
    	}, function() {
    		carousel.startAuto();
    	});
    }

    function onSlide(carousel, item, current_page, state) {
        $('#poster_controls ul li a').each(function() {
            if ($(this).attr('id') == 'page' + current_page) {
                $(this).parent().addClass('current');
            }
            else {
                $(this).parent().removeClass('current');
            }
        });
    }
    
    $('#poster').jcarousel({
		auto: 8,
		animation: 250,
		easing: 'linear',
		scroll: 1,
		wrap: 'both',
		initCallback: poster_init,
		itemFirstInCallback: onSlide,
		buttonNextHTML: null,
		buttonPrevHTML: null
	});
}

function galleryCarousel() {
	function carouselInit(carousel) {
		
		var target_gallery = "#photo_gallery_";
		var pages = $('' + target_gallery + ' .story_gallery').children().size(); // Number of pages (displays max of 3 skyboxes per page)			
		
        // Create "next" and "previous" controls
        var controls_list = $('' + target_gallery + ' ul.story_gallery'); // Find this element once and reuse it
        var controls = "<a href='" + target_gallery + "' class='carousel_control carousel_prev'>Previous</a><a href='" + target_gallery + "' class='carousel_control carousel_next'>Next</a>";
        controls_list.after(controls);

		// Bind click function to "next" button
		$("" + target_gallery + ".carousel_next").bind('click', function() {
			carousel.next();
			return false;
		});

		// Bind click function to "previous" button
		$("" + target_gallery + ".carousel_prev").bind('click', function() {
			carousel.prev();
			return false;
		});
	}
		
	$('.story_gallery').jcarousel({
		initCallback: carouselInit,
		scroll: 1,
		animation: 200,
		wrap: "both",
		buttonNextHTML: null,
		buttonPrevHTML: null
	});
}

function navPosition() {
    /*
    Positions tertiary and quaternary navigation dropdowns based on their proximity the right edge of the 
    page container.  Assumes the page container is 994px wide and nav drop downs are 150px wide.
    
    Tertiary nav: applying .shift_left will cause the drop down to align it's right edge with the right edge
    of the parent category.
    
    Quaternary nav: applying .pop_left will cause the nav to pop to the left side of the tertiary nav instead
    of the default right side.
    */
    var wrapper_offset = $("#page_wrapper").offset();
    var nav_offset = 844 + wrapper_offset.left;
    
    // If the tertiary nav will overlap the right edge of the wrapper div, apply .shift_left
    $("ul.tertiary_nav").each(function() {
       var offset = $(this).offset();
       if (offset.left > nav_offset) {
           $(this).addClass("shift_left");
       } 
    });
    
    // If the quaternary nav will overlap the right edge of the wrapper div, apply .pop_left
    $("ul.quaternary_nav").each(function() {
        var offset = $(this).offset();
        if (offset.left > nav_offset) {
            $(this).addClass("pop_left");
       }
    });
}

function dropCap(selector) {
	var firstElement = $(selector);
	var newElement = firstElement.clone(true);
	
	newElement.addClass("first_graph");
	if($.browser.safari || $.browser.opera) { newElement.addClass("safari_opera");}
	firstElement.replaceWith(newElement);
}

function updownInit(item_selector, container_selector, ad_selector, ad_location, cookie_name) {
	/*
	Call this function inside $(document.ready())
	item_selector is used to get the items that are reorderable, ie ".section"
	container_selector is used to get the containing element of the reoroderable items, ie ".sections"
	ad_selector is used to choose the element containg the locked ad, ie ".sections .leaderboard"
	ad_location is the number of items that should appear before the ad, ie 2. If no ad is used, specify null
	cookie_name is used to store the order of items in a named cookie, ie "updown_home"
	*/
	
	// If a cookie is set, reorder the sections
	if ($.cookie(cookie_name)) {
		var itemIDs = $.cookie(cookie_name).split(",") || []; // Get the list of #ids from the cookie
		
		var itemsList = $(item_selector); // Get the jquery object containing all the sections on the page
		var itemsContainer = $(container_selector); // Get the jquery object with the div containing the sections
		
		var itemsLength = itemIDs.length-1; // Get the total number of items in the list
		
		// If ad_location is null, set a breakpoint at the last item. Otherwise, break at the ad
		if (!ad_location) {
			var breakPoint = itemsLength;
		} else {
			var breakPoint = ad_location-1;
		}
		
		// Loop through the items until the breakpoint.
		for (var i=breakPoint; i >= 0; i--) {
			var item = $("#" + itemIDs[i]); // Get each item ID by combining the id selector "#" with the id name from the array
			if (item.length > 0) {
				item.prependTo(itemsContainer); // Remove the item from its current position and prepend the item to the beginning of the container
			}
		}
		
		// If there is an ad_location, loop from the ad_location until the end
		if (ad_location) {
			for (var i=ad_location; i <= itemsLength; i++) {
				var item = $("#" + itemIDs[i]); // Get each section ID by combining the id selector "#" with the id name from the array
				if (item.length > 0) {
					item.appendTo(itemsContainer); // Remove the item from its current position and append the item to the beginning of the container
				}
			}
		}
		
		// Get the list of items now that they've been reordered
		var newItemsList = $(item_selector);
	}
	// Write Up and Down arrows into the titlebar
	writeArrows(item_selector, ad_selector, ad_location, cookie_name);
}

/* Writes arrows to all necessary elements */
function writeArrows(item_selector, ad_selector, ad_location, cookie_name) {
	var items = $(item_selector);
	for (var i = 0; i < items.length; i++) {
		var item = $(items[i]); // The item being written to
		var itemID = "#" + item.attr("id"); // The ID of the item
		var titlebar = $(itemID + " .titlebar"); // The titlebar element (likely a div) of the item
		
		// Create the unordered list with necessary list items, links
		var upDownLinks = '<ul class="updown"><li class="up">';
		
		// If we're not in the first item in the list, make the up arrow a link. Otherwise, don't make it a link
		if (i != 0) {
			upDownLinks += '<a href="' + itemID + '" title="Reorder Section Up: ' + itemID + '">Up</a>';
		} else {
			upDownLinks += 'Up';
		}
		
		// If we're not in the last item in the list, make the down arrow a link. Otherwise, don't make it a link
		upDownLinks += '</li><li class="down">';
		if (i != (items.length - 1)) {
			upDownLinks += '<a href="' + itemID + '" title="Reorder Section Down: ' + itemID + '">Down</a>';
		} else {
			upDownLinks += 'Down';
		}

		upDownLinks += '</li></ul>'; // Close the unordered list

		titlebar.append(upDownLinks); // Append the unordered list to the end of the titlebar
	}
	
	
	// Capture all clicks on section up links
	$('li.up a').click(function() {
		moveItem($(getTargetID($(this))), "up", item_selector, ad_selector, ad_location, cookie_name);
		return false;
	});

	// Capture all clicks on section down links
	$('li.down a').click(function() {
		moveItem($(getTargetID($(this))), "down", item_selector, ad_selector, ad_location, cookie_name);
		return false;
	});
	
	// Register these clicks with Apptap 
	registerAppTapEvent("li.up a, li.down a", "Event63", false);
}
/* Moves items that are reorderable */
function moveItem(item, direction, item_selector, ad_selector, ad_location, cookie_name) {
	var items = $(item_selector); // The array of reorderable items
	var itemIndex = items.index(item); // The index of the moving item in the array
	
	var prevItem = $(items.get(itemIndex-1)); // The item before the one being moved
	var nextItem = $(items.get(itemIndex+1)); // The item after the one being moved
	
	// Reorder the items after fading the item out by using the fadeOut callback
	item.fadeOut("fast", function() {
		// Move the items
		if (direction == "up") {
			item.insertBefore(prevItem); // Moves the item in front of the previous item
			
			// If the item is immediately after the ad, move the previous item to beneath the ad, before the next item
			if (itemIndex == ad_location) {
				prevItem.insertBefore(nextItem);
			}
		}
		else if (direction == "down") {
			item.insertAfter(nextItem); // Moves the item after the next item
			
			// If the item is immediately before the ad, move the next item to above the ad, after the previous item
			if (itemIndex == ad_location-1) {
				nextItem.insertAfter(prevItem);
			}
		}
		
		// Remove the arrows from all items, and replace them. This is done because first/last items don't need up/down links
		$("ul.updown").remove();
		writeArrows(item_selector, ad_selector, ad_location, cookie_name);
		
		// Set the cookie with the order of the items
		var order = "";
		var movedItems = $(item_selector);
		
		// Add each item's id to the order string, followed by a comma
		movedItems.each(function () {
			order = order + this.id + ",";
		});
		order = order.substring(0,order.length-1); // Ignore the last character, which is a comma
		
		$.cookie(cookie_name, order, { expires: 730 }); // Set the cookie
		
	});
	item.fadeIn("slow"); // Put the moved item in its new place slowly
	
	// Have a party
}
function getTargetID(item) {
	// Returns the last bit of a url split by "/". So /news/entertainment/#anchorText returns "#anchorText"
	// Item must be a jquery object, ie $(this) not this
	var href = item.attr("href");
	var bits = href.split(/\//);
	var id = bits[bits.length-1];
	if (id.charAt(0) == "#") {
		return id; // If the last bit begins with an anchor, return it
	} else {
		return null;
	}
}
function fontResize(cookie_name) {
    if ($.cookie(cookie_name)) {
        
        switch($.cookie(cookie_name)) {
            case "14":
                $('#article_body').css('font-size', 14);
                
                // Add active class to the clicked button

                if (!$('a#font_small').hasClass('active')) {
                    $('a#font_small').addClass('active');
                }

                // Remove .active on the other two buttons if it exists

                if ($('a#font_default').hasClass('active')) {
                    $('a#font_default').removeClass('active');
                }

                if ($('a#font_large').hasClass('active')) {
                    $('a#font_large').removeClass('active');
                }
                break;
            
            case "16":
                $('#article_body').css('font-size', 16);

                // Add active class to the clicked button

                if (!$('a#font_default').hasClass('active')) {
                    $('a#font_default').addClass('active');
                }

                // Remove .active on the other two buttons if it exists

                if ($('a#font_small').hasClass('active')) {
                    $('a#font_small').removeClass('active');
                }

                if ($('a#font_large').hasClass('active')) {
                    $('a#font_large').removeClass('active');
                }
                break;
                
            case "18":
                $('#article_body').css('font-size', 18);

                 // Add active class to the clicked button

                if (!$('a#font_large').hasClass('active')) {
                    $('a#font_large').addClass('active');
                }

                // Remove .active on the other two buttons if it exists

                if ($('a#font_small').hasClass('active')) {
                    $('a#font_small').removeClass('active');
                }

                if ($('a#font_default').hasClass('active')) {
                    $('a#font_default').removeClass('active');
                }
                break;
        }
    }
    else {
        $('a#font_default').addClass('active');
    }
    
    // Set #article_body to large font size  
    
    $('a#font_large').click(function() {
        $('#article_body').css('font-size', 18);
        $.cookie(cookie_name, 18);
       
        // Add active class to the clicked button
       
        if (!$(this).hasClass('active')) {
            $(this).addClass('active');
        
            // Remove .active on the other two buttons if it exists
        
        if ($('a#font_default').hasClass('active'))
            $('a#font_default').removeClass('active');
        
        if ($('a#font_small').hasClass('active'))
            $('a#font_small').removeClass('active');
        }
       
        return false; 
    });
    
    // Set #article_body to default font size
    
    $('a#font_default').click(function() {
        $('#article_body').css('font-size', 16);
        $.cookie(cookie_name, 16);
       
        // Add active class to the clicked button
       
        if (!$(this).hasClass('active')) {
            $(this).addClass('active');
        
        // Remove .active on the other two buttons if it exists
        
        if ($('a#font_large').hasClass('active'))
            $('a#font_large').removeClass('active');
        
        if ($('a#font_small').hasClass('active'))
            $('a#font_small').removeClass('active');
       }
       
       return false; 
    });
    
    // Set #article_body to small font size
    
    $('a#font_small').click(function() {
        $('#article_body').css('font-size', 14);
        $.cookie(cookie_name, 14);
       
        // Add active class to the clicked button
       
        if (!$(this).hasClass('active')) {
            $(this).addClass('active');
        
        // Remove .active on the other two buttons if it exists
        
            if ($('a#font_default').hasClass('active'))
                $('a#font_default').removeClass('active');
        
            if ($('a#font_large').hasClass('active'))
                $('a#font_large').removeClass('active');
        }
       
       return false; 
    });
}

function searchFilter(url) {
	$("input#search_button").remove();

	$(".ajax_loader").ajaxStart(function() {
		$(this).show();
		$(this).next().fadeTo("medium", 0.25);
	});

	$(".ajax_loader").ajaxStop(function() {
		$(this).hide();
		$(this).next().fadeTo("medium", 1);
	});

	$("#browse_search_form .vSelectField").change(function () {
        var query = "";   

		$("#browse_search_form .vSelectField").each(function(i){
			if ($(this).val() != "") {
				query += $(this).attr("name") + "=" + $(this).val() + "\&";
			}
		});

		query = query.substring(0, query.length-1);
		
		$.ajax({
			type: "GET",
			url: url,
			data: query,
			dataType: "html",
			success: function(results){
				$("ul.browse_list").html(results);
			}
		});
	});
}

function yahooMap(id, lat, long, name, address, city, zip, width, height) {
	// Create a map object
	var mapsize = new YSize(width, height);
	var map = new YMap(document.getElementById('mapwindow_' + id), YAHOO_MAP_REG, mapsize);

	// Add map controls
	map.addZoomShort();
	map.disableKeyControls();
	map.removeZoomScale(); 

	// Create geopoint and marker
    var geopoint = new YGeoPoint(lat, long);
    var newMarker = new YMarker(geopoint);
    
	// Insert address into marker
    var markerMarkup = "<div style='padding: 3px 7px; font-family: Verdana; font-size: 0.8em; width: 175px;'><strong>" + name + "</strong><br/>" + address +"<br/>" + city + " " + zip + "</div>";
    
	// Bind marker to click event
    YEvent.Capture(newMarker, EventsList.MouseClick,
        function(){
           newMarker.openSmartWindow(markerMarkup) ;
        });
        
	// Add marker to map, center on marker and set zoom to 5
    map.addOverlay(newMarker);
	map.drawZoomAndCenter(geopoint, 5);
	
	// Handle clicks on map buttons - slide down to reveal map
    $("#mapbutton_" + id).click(function () {
		$(this).next('div.list_map').slideToggle();
		return false;
	});
}

$.fn.popmenu = function(options) {
    var defaults = {
        menu: ".popmenu",
        activeClass: false,
        time: 1500,
        speed: "",
        effect: ""
    };
    var options = $.extend(defaults, options);
    var active_menu = null;
    var timeout;
    
    return this.each(function() {
        
        var button = $(this);
        var menu = $(this).next();
        
        button.click( function(e) {
            clearTimeout(timeout);
            
            // If the target menu is hidden, close all open menus and open target menu
            if (menu.is(':hidden')) {
                // Close all open menus and remove active state on related buttons
                $("" + options.menu + ":visible").each( function() {
                    $(this).hide(options.speed);
                    $(this).prev().removeClass(options.activeClass);
                });
                
                menu.show(options.speed);
                if (options.activeClass != false) {
                    button.addClass(options.activeClass);
                }
            }
            // If the target menu is already visible, hide it
            else {
                menu.hide(options.speed);
                if (options.activeClass != false) {
                    button.removeClass(options.activeClass);
                }
            }
            active_menu = menu.index(menu);
            
            return false;
        });
        
        // Clear timeout if user mouses back over the button
        button.mouseover( function() {
           clearTimeout(timeout);
           active_menu = menu.index(menu);
        });
        
        // Clear timeout if user mouses back over the menu
        menu.mouseover( function() {
            clearTimeout(timeout);
            active_menu = menu.index(menu);
        });
        
        // When mouse leaves the button, start a timer to close the menu
        button.mouseout( function() {
            timeout = setTimeout(
            function() {
                if(options.activeClass != false){
                    button.removeClass(options.activeClass);
                }
                menu.hide(options.speed);
            }
            ,options.time);
            
          active_menu = null;
        });
        
        // When mouse leaves the menu, start a timer to close the menu
        menu.mouseout( function () {
            timeout = setTimeout(
            function() {
                if(options.activeClass != false) {
                    button.removeClass(options.activeClass);
                }
                menu.hide(options.speed);
            }
            ,options.time); 
            
            active_menu = null;
        });
        
        // Handle clicks that are not on a button or menu
        $(document).click(function(e) {
            if (active_menu == null) {
                $(options.menu + ":visible").each( function() {
                    $(this).hide(options.effect, options.speed);
                    $(this).prev().removeClass(options.activeClass);
                });
            }
        });
        
    });
};

ratingSubmit = function(value, link){
	value = value || 0;
	if (value != 0) {
		// User has rated this
		var f = $(this.form);
		
		if(!f.hasClass("user_rating_form")) {
			f.addClass("user_rating_form");
		}
	} else {
		// User has cleared his rating
		var f = cancelThisForm;
		f.removeClass("user_rating_form");
	}
	$.post(f.attr("action"), {rating: value}, function(data, textStatus) {
		if (value == 0) {
			// Since user has cleared the rating, remove the users rating info and reinitialize this form
			// To get the overall rating
			var newData = eval("(" + data + ")");
			var newRating = newData.rating
			
			
			var inputs = f.children('input[type=radio].rating-star');
			var input = inputs.filter("[value=" + newRating + "]");
			var overallInput = $(input[0]);
			
			overallInput.attr("checked", "checked");
			inputs.attr("class", "rating-star");
			f.find('span.star-rating-control').remove();
			
			initContentRatings(inputs, f);
		}
	});
}

initContentRatings = function(inputObjects, cancelScope){
	inputObjects.rating( {callback: ratingSubmit} );
	$('.star-rating-readonly').click(function() {
		alert("Please login to rate content");
	});
	cancelScope.find('div.rating-cancel a').click(function() {
		cancelThisForm = $($(this).parents("form")[0]);
	});
}

initCellarBD = function() {
	/*
	If a site has business directory links in its footer, this function hides the directory links,
	creates a link that toggles their display, and handles the toggling.
	*/
	if ($("#business_directory").length > 0) {
		var bd = $('#business_directory_prompt'); // The dt for the business directory
		var bdLinks = $("#business_directory_links"); // The links inside the business directory
		bdLinks.hide(); // Hide the links
		bd.append('<a href="#business_directory"> See directory links</a>'); // Add a link for user show/hide the links
		var bdToggle = $('#business_directory_prompt a'); // Get the toggle link that was just added

		bdToggle.click(function(clickEvent) {
			// On each click, prevent the default anchor action, then toggle the bdLinks display
			clickEvent.preventDefault();
			var a = $(this);
			var t = a.text(); // The text of the toggle link

			bdLinks.toggle(); // Show/hide the links
			if (t.search('See') >=0) {a.text(t.replace(' See', ' Hide'));} else { a.text(t.replace(' Hide', ' See'));} // Swap the link verbage
		});
	}
}
function eventTabs() {
	$("input#search_button").remove(); // Remove the search button for results filtering

    // On each click for a day, submit AJAX request and load that day's events and reload filters
	$("#events_browse ul.cal_tab_header a").click(function () {
	    // Hide & show calendar tab
		if ($(this).hasClass("browse_cal")) {
			$(".search_results_wrapper").hide();
			$("#browse_cal").show();
		} else {
			$("#browse_cal").hide();
			$(".search_results_wrapper").show();
		}
		
		// Loader div when AJAX request is submitted
		$("#day_load").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#day_load").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});
		
		$(this).parent().siblings().removeClass("ui-tabs-selected"); // Remove active state from all other days
		
		$(this).parent().addClass("ui-tabs-selected"); // Set clicked day to be active
		
		query = "start_date=" + $(this).attr("value") + "&framing=event_day_list"; // Create query based on the clicked day
		
		$.ajax({
			type: "GET",
			url: "/events/",
			data: query,
			dataType: "html",
			success: function(results){
			    // Insert results into the wrapper div
				$(".search_results_wrapper").html(results);
				
				// Rebind event handler after new content is loaded, otherwise filters will fail
				$("input#search_button").remove();
				
				$("#browse_search_form .vSelectField").change(function () {
		            $("#filter_load").ajaxStart(function() {
		                $(this).show();
		                $(this).next().fadeTo("medium", 0.25);
					});

					$("#filter_load").ajaxStop(function() {
		                $(this).hide();
		                $(this).next().fadeTo("medium", 1);
					});
					
					query = filterQuery();	// build query string from form fields
		
					query += "&framing=event_filter_list"
		
					$.ajax({
						type: "GET",
						url: "/events/",
						data: query,
						dataType: "html",
						success: function(results){
							$("ul.browse_list").html(results);
						}
					});
				});
			}
		});
		return false;
	});
	
	// Handle selections in form drop-downs - submit AJAX request with updated query each time a selection is made
	$("#browse_search_form .vSelectField").change(function () {
	    // Hide / show loader div when AJAX request submitted
		$("#filter_load").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#filter_load").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});
		
		query = filterQuery();	// Build query string from form fields
		
		query += "&framing=event_filter_list"  // Append framing parameter
		
		$.ajax({
			type: "GET",
			url: "/events/",
			data: query,
			dataType: "html",
			success: function(results){
			    // Insert results into the list
				$("ul.browse_list").html(results);
			}
		});
	});
	
	// Creates a query string from the form select fields
	function filterQuery(query) {
		var query = "";
		
		// Get the date for the day tab that was clicked
		$("#events_browse ul.cal_tab_header li").each(function () {
			if ($(this).hasClass("ui-tabs-selected")) {
				date = $(this).children("a").attr("value");
			}
		});
		
		// Iterate through each drop-down and build query string
		$("#browse_search_form .vSelectField").each(function(i){
			if ($(this).val() != "") {
				query += $(this).attr("name") + "=" + $(this).val() + "\&";
			}
		});
		
		return query += "&start_date=" + date;
	}
}
//function oc(a) { var o = {}; for(var i=0;i<a.length;i++) { o[a[i]]=''; } return o; } // Converts objects to arrays
function execAppTapEvent(trigger, eventName, isMacro) {
	var trigger = $(trigger);
	var title = trigger.attr("title");
	sendEvent(trigger, eventName, title); // Tracks clicks for all events
	if (isMacro) { retarget(getEventPath(trigger), title); } // Retargets apptap for macro events
}

function registerAppTapEvent(selector, eventName, isMacro) {
	$(selector).click(function() {
		execAppTapEvent(this, eventName, isMacro);
	});
}

function getEventPath(trigger) {
	if (path[-1] != "/") { path += "/"; } // Make sure there's a trailing /
	return path + trigger.attr("href"); // Adds the trigger's href anchor to the path
}

function initAsphaltAppTap() {
	registerAppTapEvent(".macro_tab_header li a", "Event60", true);
	registerAppTapEvent("#content_wrapper :not('#secondary_content') .tab_header:not('.macro_tab_header') li a", "Event61", false);
	registerAppTapEvent("#secondary_content .tab_header li a", "Event62", false);
}
/* COMMENTS */
function loadComments(baseurl, page, comment) {
	var getComment = comment || 0;
	var getPage = page || 0;
	var getURL = baseurl + getPage + "/";
	var loaderElement = '<div id="filter_load" class="ajax_loader" style="display: block;"><img src="' + loadImgURL + '" alt="Loading content" /><p>&nbsp;&nbsp;&nbsp;Loading...</p></div>';
	var jcomments = $("#comments_container");
	
	jcomments.html(loaderElement);
	
	if (getComment != 0) {
		var d = {comments_id: getComment};
	} else {
		var d = {};
	}
	
	$.get(getURL, d,
		function(data){
			jcomments.html(data);
			handleCommentsLinks();
			updateCommentCounts(".dynamic_comment_count");
			if (d['comments_id'] && firstCommentsLoad) {
				// There is a comment to jump to on first load, before next/prev have been clicked
				//window.location.hash = "c" + d['comments_id'].toString();
				$.scrollTo($("#c" + d['comments_id'].toString()));
			}
			firstCommentsLoad = false;
		}
	);
}
function revealComment(element) {
	var comment = $("#ccr" + element);
	var warning = $("#cch" + element);
	//var comment = document.getElementById('ccr' + element);
	//var warning = document.getElementById('cch' + element);

	if (comment.length > 0 && warning.length > 0) {
		comment.show();
		warning.hide();
	}
}
function writeCommentCookie(action) {
	document.cookie = "hidecomments=" + encodeURIComponent(action) + "; path=/; max-age=" + (60 * 60 * 24 * 365);
}
function toggleComments(toggleLink, commentsDiv) {
	if (toggleLink.text() == "Hide") {
		// Hide Comments
		commentsDiv.hide();
		writeCommentCookie("out");
		toggleLink.text("Show");
	} else {
		// Show Comments
		loadComments(commentsURL, 0, 0);
		commentsDiv.show();
		writeCommentCookie("in");
		toggleLink.text("Hide");
	}
}
function handleCommentsLinks() {
	$(".comments_prev").click(function(event) {
		// Previous link
		event.preventDefault();
		$.scrollTo($("#comments"));
		loadComments(commentsURL, commentsPreviousPage, 0);
	});
	$(".comments_next").click(function(event) {
		// Next link
		event.preventDefault();
		$.scrollTo($("#comments"));
		loadComments(commentsURL, commentsNextPage, 0);
	});
	$("select.comments_pages_select").change(function() {
		$.scrollTo($("#comments"));
		var selectedOption = $(this).children("option:selected");
		var re = /\d+/;
		var newIndex = re.exec(selectedOption.attr("class"))[0] * 1; // Gets the new index from the id of the selected option
		loadComments(commentsURL, newIndex, 0);
	});
	
}
function updateCommentCounts(destinationSelector) {
	var re = /\d+/;
	var commentCount = re.exec($("#comment_wrapper .comment_list_wrapper:first").attr("id"))[0] * 1;
	if ($('#titlebar_comment_count').length == 0) {
		// Comment count is not yet in the titlebar
		var titlebarCommentCount = ' <span id="titlebar_comment_count">&raquo; <span class="' + destinationSelector.replace(".","") + '"></span></span>';
		$("#comments .titlebar:first h3:first").append(titlebarCommentCount); // Add comment count container to the titlebar
	}
	$(destinationSelector).each(function() {
		$(this).text(commentCount); // Update all dynamic comment counts
	});
}
function initComments() {
	var commentsDiv = $("#comments");
	var toggleDiv = $("#comment_wrapper");
	if (commentsDiv.length > 0) {
		if (hideComments == true) {
			toggleDiv.hide(); // Hide comments div
			var toggleText = 'Show';
		} else {
			var toggleText = 'Hide';
		}
		var toggleUL = '<ul class="deeplinks"><li><a href="#comments" id="comments_toggle">' + toggleText + '</a></li></ul>';
		var commentsTitlebar = $("#comments .titlebar:first");
		commentsTitlebar.append(toggleUL); // Write the show/hide link to the titlebar

		$("#comments_toggle").click(function(event) {
			// Handle the click event of the show/hide link
			event.preventDefault();
			toggleComments($(this), toggleDiv);
		});

		handleCommentsLinks();
	}
}
function showMobilePrompt(mobileURL) {
	var width = getBrowserWidth();
	if ($.cookie("preventMobileRedirect") && !$.cookie("hideMobilePrompt") && width != 0 && width <= 800) {
		var prompt = '<div id="mobile_prompt" style="width: 994px; height: 60px; margin: 0 auto 10px;line-height: 60px; font-size: 24px;"><a id="visitMobileSite" href="' + mobileURL + '" style="margin-left: 15px;">Visit our mobile-optimized site</a><a id="hideMobilePrompt" href="#" style="font-size: 18px; color: #444; margin-left: 15px; text-transform: uppercase">Hide this message</a></div>';
		$("#utilities_wrapper").prepend(prompt); // Write the prompt into the utilities header
		// Capture clicks on the hide link to set a cookie to never show this again
		$("#hideMobilePrompt").click(function(e) {
			e.preventDefault(); // Keep the link from clicking through
			$("#mobile_prompt").remove(); // Remove the div
			$.cookie("hideMobilePrompt", 1, { expires: 365 }); // Set cookie so that it does not show anymore
		});
		
		// Capture clicks on the visit link to remove the prevent redirect cookie
		$("#visitMobileSite").click(function() {
			$.cookie("preventMobileRedirect", null);
		});
	}
}