// functions.js
// v24

function fixHitCount(){
    var random = Math.floor(Math.random()*9999999999);
    var myURL = "http://www.food2.com/fixHits.html?v=" + random;

    if($("#hitCounter").length == 0){
        $("body").append('<iframe id="hitCounter" width="0" height="0" frameborder="0"></iframe>');
        $("#hitCounter").css({"visibility":"hidden"});
    }
    $("#hitCounter").attr("src",myURL);
    return;
}


String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

/**
 *  Dynamic Lead Module
 */
function showFeaturedRecipe(inc){
    if(!recipes){ alert("No recipes"); return false; }

    $("#recipe-inner").fadeOut('slow');

    /* Check to see if were going forward or backward */
    if(inc < 0){ curr_recipe--; }else{ curr_recipe++; }

    if(curr_recipe > total_recipes){ return false; }

    /* If were at the last image, then reset the counter */
    if( (curr_recipe + 1) == total_recipes){
        $("#next_recipe").addClass("disabled");
        $("#next_recipe").html("<span>Next Recipe &raquo;</span>");
    }else{
        $("#next_recipe").removeClass("disabled");
        $("#next_recipe").html("<a href='#' onclick='showFeaturedRecipe(1);'><span>Next Recipe &raquo;</span></a>");
    }

    if( curr_recipe <= 0){
        $("#prev_recipe").html("<span>&laquo; Previous Recipe</span>");
        $("#prev_recipe").addClass("disabled");
    }else{
        $("#prev_recipe").removeClass("disabled");
        $("#prev_recipe").html("<a href='#' onclick='showFeaturedRecipe(-1);'><span>&laquo; Previous Recipe</span></a>");
    }

    if(recipes[curr_recipe]){
        $(".featuredimg").attr("href", "/recipes/" + recipes[curr_recipe].alias);
        $(".featuredimg img").attr("src", recipes[curr_recipe].image_url);
        $("#recipe_title").html(recipes[curr_recipe].title);
        $("#recipe_title").attr("href", "/recipes/" + recipes[curr_recipe].alias);
        $("#recipe_preptime").html(recipes[curr_recipe].preptime);
        $("#recipe_cooktime").html(recipes[curr_recipe].cooktime);
        $("#recipe_difficulty").html(recipes[curr_recipe].difficulty);
        $("#recipe_rating").attr("src", recipes[curr_recipe].rating);
        $("#recipe_author").html(recipes[curr_recipe].recipe_author);

        if(recipes[curr_recipe].author_url){
            $("#author_url").html(recipes[curr_recipe].author_url);
            $("#author_url").show();
        }else{
            $("#author_url").hide();
        }
        $(".st-left h2 span").html( (curr_recipe + 1) + " of " + total_recipes);
        
        $("#recipe-inner").fadeIn('slow');
    }else{
        return false;
    }

    fixHitCount();
    reloadBigBox();

    return false;

}

function reloadBigBox(){
    setDartEnterpriseBanner("BIGBOX", getDartEnterpriseUrl("BIGBOX", 5));
}

function addFacebookURLRef(url) {
	if(typeof url == "undefined") {return "";}
	return url.indexOf("?")>=0
		? url += "&utm_source=facebook"
		: url += "?utm_source=facebook";
}


function facebookPublish(title, actionedAnAssetType, description, callback) {
	// Generate strings
	
	title = title.replace(" Tip - Food2", "");
	title = title.replace(" Blog - Food2", "");
	title = title.replace(" Video - Food2", "");
	title = title.replace(" - Food2", "");
	
	
	var storyCaption =  "{*actor*} " + actionedAnAssetType + " at food2.com.";
	var storyTitle = "Check out '" + title + "' on food2.com!";
	var storyLinkText = "Check it out now!";
	var storyBody = description;
	/*
	var pathToMedia =   {
							type: 	"image",
							src: 	this.addFacebookURLRef(thumbnailUrl), 
							href: 	this.addFacebookURLRef(window.location.href)
						}
	*/

	//var	hasImages =		substituteData.mediaThumbnail && substituteData.mediaUrl;
	var dialogPrompt = 	"Tell your Facebook friends about food2!";
	var storyLink = 	this.addFacebookURLRef(window.location.href);

	var fbAttachment = {
		name:			storyTitle,
		href: 			storyLink,
		caption: 		storyCaption,
		description: 	storyBody,
		media:			[],
		action_links: 	[
             	 		{text:	storyLinkText,
             	 		 href:	storyLink}
             			]
	}
	var actionLinks = [
       	{ 'text' : 'food2.com', 'href' : 'www.food2.com' }
   	]; 
	
	// Link to an image if we have enough data for it
	/*
	if (hasImages) {
		fbAttachment.media.push(pathToMedia);
	}
	*/
	// now publish 
	FB.Connect.streamPublish(
 		'', 
		fbAttachment, 
		actionLinks, 
		null,
		dialogPrompt,
    	callback
    );
}
									
$(document).ready(function(){
    function orderby(){

    }
    // Search Actions

    // Limit search to 100 characters
    $('#mod_search_searchword').keyup(function(){
	var maxlen = 100;
	var txt = $(this).val();
	var txtLen = txt.length;
	if(txtLen >= maxlen){
	    var oldTxt = txt.substr(0,maxlen);
	    $(this).val(escape(oldTxt));
	    return false;
	}
    });

    $('#mod_search_searchword').focus(function(){
	$thisinput = $(this);
	if (this.value === 'Enter search term'){
	    $thisinput.val('');
	}
    })
    .blur(function(){
	if (this.value === ''){
	    $thisinput.val('Enter search term');
	}
    });
    // no entry
    $('#searchGo').click(function(){
	$input = $('#mod_search_searchword').val();
	if ($input === '' || $input === 'Enter search term'){
	    $('#noquery').show();
	    return false;
	}else{
	    this.form.searchword.focus();
	}
    });

    $('#recipesearchsub').click(function(){
	$input = $('#searchterms').val();
	if ($input === '' || $input === 'Search'){
	    $('#noquery-2').show();
	    return false;
	}else{
	    this.form.searchword.focus();
	}
    });

    $('#tipsearchsub').click(function(){
	$input = $('#searchterms').val();
	if ($input === '' || $input === 'Search'){
	    $('#noquery-2').show();
	    return false;
	}else{
	    this.form.searchword.focus();
	}
    });

    $('#noquery a.closeMod').click(function(){
	$('#noquery').hide();
    });

    $('#noquery-2 a.closeMod').click(function(){
	$('#noquery-2').hide();
    });

    // Autocomplete
    $("#mod_search_searchword").autocomplete("/js/autocomplete.php", {
	selectFirst: false,
	minChars: 3,
	max: 7,
	width: 290
    });
    $(".searchrecipes #searchterms").autocomplete("/js/autocomplete.php", {
	selectFirst: false,
	minChars: 3,
	max: 7,
	width: 290
    });

    $(".searchtips #searchterms").autocomplete("/js/autocomplete.php", {
	selectFirst: false,
	minChars: 3,
	max: 7,
	width: 290
    });

    // Friend Comments
    $('h3.friendComments a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$('.nonFriendComment').hide();
	$thisLink.addClass('active');
	return false;
    });

    $('h3.allComments a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$('.nonFriendComment').show();
	$thisLink.addClass('active');
	return false;
    });

    // Review Tabs
    $tabvalue = jQuery.url.param("tab");

    if ($tabvalue === 'suggest' || $tabvalue === undefined){
	$('h3.reviewtab a.active').removeClass('active');
	$('a#suggest').addClass('active');
	$('#recipeSuggestions').show();
	$('#recipeTurnedOut, #recipeRemindsMe').hide();	
    }
    if ($tabvalue == 'turnedout'){
	$('h3.reviewtab a.active').removeClass('active');
	$('a#turnedout').addClass('active');
	$('#recipeTurnedOut').show();
	$('#recipeSuggestions, #recipeRemindsMe').hide();
    }
    if ($tabvalue == 'remindsme' || $tabvalue == 'reminds'){
	$('h3.reviewtab a.active').removeClass('active');
	$('a#reminds').addClass('active');
	$('#recipeRemindsMe').show();
	$('#recipeSuggestions, #recipeTurnedOut').hide();
	$('#uploadPanel').hide();
    }
    
    $("#emailFriendForm").validate( {
	errorContainer: $("#errorContainer"),
	rules: {
	    sendTo:{
		multiemail:true
	    }
	},
	messages: {
	    yourName: "Please enter your name.",
	    yourEml: "Please enter your email address.",
	    sendTo: "Please enter valid recipient addresses."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    /** Photo Gallery End Frame - Email a Friend **/
    $("#endframe_emailFriendForm").validate( {
	errorContainer: $("#endframe_errorContainer"),
	rules: {
	    sendTo:{
		multiemail:true
	    }
	},
	messages: {
	    yourName: "Please enter your name.",
	    yourEml: "Please enter your email address.",
	    sendTo: "Please enter valid recipient addresses."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    /* DV */
    // Tag Cloud on Blog section page
    var cloudtext =  $("div#tagcloud_com").html();
    $("span#tagcloud_mod").html(cloudtext);

    /* DV */
    $('.errorContainer').css({
	display:"none"
    });

    $(".submitNotifications").click(function(){
	// validate and process form
	// first hide any error messages
	$('.submitNotifications').val("Saving selections...");
	$('.submitNotifications').css({
	    'font-style':"italic"
	});

	// Check to see if they selected primary or secondary email.
	var primaryEmail = $('[name=primaryEmail]').fieldValue();
	var pemail = $("input#pemail").val();
	var semail = $("input#semail").val();
	var email;
	if(primaryEmail == 1){
	    email = pemail;
	}else if(primaryEmail !== 1 && semail !== ""){
	    email = semail;
	    $("#pemailTxt").html(semail);
	    $("input#pemail").val(semail);
	    $("input#semail").val(pemail);
	}else{
	    email = pemail;
	}
	$("#primaryEmailP").attr('checked', true);


	if (email === "") {
	    $('#selectaserieswrap').fadeOut("fast");
	    $('.errorContainer').css({
		display:"block"
	    });
	    $('.submitNotifications').val("Get Email Reminders");
	    $('.submitNotifications').css({
		'font-style':"normal"
	    });
	    $('label[for="UrEml"] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    $("input#UrEml").focus();
	    return false;
	}

	//var dataString = 'name='+ name + '&email=' + email + '&dataphone=' + dataphone;
	var dataString=$("form").serialize();
	//alert (dataString);return false;

	$.ajax({
	    type: "POST",
	    url: "index.php?no_html=1&option=com_alerts&task=stayintouch",
	    data: dataString,
	    success: function() {
		$('.submitNotifications').val("Selections Saved!");
		$('.errorContainer').css({
		    display:"none"
		});
		$('#selectaserieswrap').fadeOut("slow");
	    }
	});
	return false;
    });


    /* DV */
    $("#reviewForm").validate( {
	errorContainer: $("#cmt-errorContainer"),
	messages: {
	    star1: "Please enter a rating."
	},
	errorElement: "li",
	submitHandler: function(){
	    addComment(false);
	},
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    $("#emailReminderForm").validate( {
	errorContainer: $("#errorContainer"),
	messages: {
	    yourName: "Please enter your name.",
	    yourEml: "Please enter your email address."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    $("#masterContactForm").validate( {
	onfocusout: false,
	onkeyup: false,
	errorContainer: $("#errorContainer"),
	messages: {
	    first: "Please enter your first name.",
	    last: "Please enter your last name.",
	    email: "Please enter a valid email address.",
	    confirm: "Please confirm your email address.",
	    postal: "Please enter your postal code.",
	    blog_url: "Please enter your blog URL.",
	    msgmsg: "Please enter your message."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+']').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    $("#addCommentForm").validate( {
	onfocusout: false,
	onkeyup: false,
	errorContainer: $("#cmt-errorContainer"),
	messages: {
	    name: "Please enter your first name.",
	    email: "Please enter your email address.",
	    anonEmail: "Please enter your email address.",
	    emlMessage: "Please enter your comment.",
	    agree: "You must check that you have read the Food2 policies and terms of use."
	},
	submitHandler: function(){
	    addComment(false);
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    element.css('outline', '2px solid #EE1C24');
	    error.appendTo('#cmt-errorContainer ul');
	}
    });

    $('#recipeupload1').blur(function(){
	if( this.value !== '') {
	    $('#nextstep').addClass('disabled').attr('onclick', '').css({
		'cursor':'default'
	    }).html('Please click upload');
	}
    });

    $('#recipeMediaSubmit').click(function(){
        /*
	var $sub = $('#recipeupload1').val();
	if( $sub === '') {
	    return false;
	}
        */
    });

    $("#masterUploadForm input").keypress(function(e){
	return !(e.keyCode == 13);
    });

    function email() {
	var request = '/index.php?option=com_recipes&task=email_friends&to=' + $('#sendTo').val() + '&fromemail=' + $('#yourEml').val() + '&fromname=' + $('#yourName').val() + '&subject=Check+this+out+from+food2.com&body=' + $('#emlMessage').val();
	aObj = new JSONscriptRequest(request);
	aObj.buildScriptTag();
	aObj.addScriptTag();
    }

    // All newsletters
    $("fieldset#required-list").find(".select-all").click(function(){
	var $this=$(this);
	var checkValue=$this.find('#all-news-toggle').text();
	if(checkValue==='I love food, give me all of them' || checkValue==='Check All'){
	    $("#required-list input[type='checkbox']").each(function(){
		$("#required-list input[type='checkbox']").attr('checked',true);
	    });
	    $this.find('#all-news-toggle').text('Whoah, uncheck all');
	}else{
	    $("#required-list input[type='checkbox']").each(function(){
		$("#required-list input[type='checkbox']").attr('checked',false);
	    });
	    $this.find('#all-news-toggle').text('I love food, give me all of them');
	}
    });

    // Validate Newsletters
    $("#newsletterform").validate( {
	errorContainer: $("#errorContainer"),
	rules: {
	    FIRST_NAME_: "required",
	    LAST_NAME_: "required",
	    email: {
		required: true,
		email: true
	    },
	    email_confirm: {
		equalTo: "#email"
	    },
	    POSTAL_CODE_: "required"
	},

	messages: {
	    FIRST_NAME_: "Please enter your first name.",
	    LAST_NAME_: "Please enter your last name.",
	    email: "Please enter a valid email address.",
	    email_confirm: "Please confirm your email address.",
	    POSTAL_CODE_: "Please enter your postal code."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    // Validate FN Newsletters
    $("#frmNewsletterSubscribe").validate( {
	errorContainer: $("#errorContainer"),
	rules: {
	    FIRST_NAME_: "required",
	    LAST_NAME_: "required",
	    email: {
		required: true,
		email: true
	    },
	    email_confirm: {
		equalTo: "#email"
	    },
	    list: "required",
	    POSTAL_CODE_: "required"
	},

	messages: {
	    FIRST_NAME_: "Please enter your first name.",
	    LAST_NAME_: "Please enter your last name.",
	    email: "Please enter a valid email address.",
	    email_confirm: "Please confirm your email address.",
	    list: "Please select a Newsletter.",
	    POSTAL_CODE_: "Please enter your postal code."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    // Validate FN Newsletters
    $("#frmNewsletterEmail").validate( {
	errorContainer: $("#errorContainer"),
	rules: {
	    email: {
		required: true,
		email: true
	    },
	    emailnew: {
		required: true,
		email: true
	    },
	    emailnew_confirm: {
		equalTo: "#newemail"
	    }
	},

	messages: {
	    email: "Please enter a valid email address.",
	    emailnew: "Please enter a new valid email address.",
	    emailnew_confirm: "Please confirm your new email address."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    // Validate FN Newsletters
    $("#frmUnsubscribe").validate( {
	errorContainer: $("#errorContainer"),
	rules: {
	    list: "required",
	    email: {
		required: true,
		email: true
	    },
	    email_confirm: {
		equalTo: "#email"
	    }
	},

	messages: {
	    list: "Please select a Newsletter.",
	    email: "Please enter a valid email address.",
	    emailnew: "Please enter a new valid email address.",
	    emailnew_confirm: "Please confirm your new email address."
	},
	errorElement: "li",
	errorPlacement: function(error, element) {
	    var id = element.attr('id');
	    $('label[for='+id+'] span').css({
		'background-color':'#FFC100',
		'color':'#162029'
	    });
	    error.appendTo('#errorContainer ul');
	}
    });

    // Vote again
    $('a.changevotelink').click(function(){
	$('#changeyourvote').hide();
	$('#voteagainWrap').show();
	$('#firstvoteWrap').show();
	return false;
    });

    // Email a friend
    $('a.emailOpen').click(function(){
	$('#emailFriendWrap').show();
	if (window.location.href.indexOf("challenge") != -1) {
	    challengeTellAFriendOmni();
	}
	return false;
    });

    $('#tellafriendlink').click(function(e){
	//getting height and width of the message box
	var height = $('#remindWrap').height();
	//calculating offset for displaying popup message
	topVal=e.pageY-(height/2)-650+"px";
	// assign the vals
	$('#emailFriendWrap').css({
	    top:topVal
	});
	$('#emailFriendWrap').show();
	return false;
    });

    //  Get reminders for challenge milestone
    /* DV */
    $('a.remindOpen').click(function(e){
	//getting height and width of the message box
	var height = $('#remindWrap').height();
	var width = $('#remindWrap').width();
	//calculating offset for displaying popup message
	leftVal=e.pageX-(width/2)-100+"px";
	topVal=e.pageY-(height/2)-400+"px";
	// assign the vals
	$('#remindWrap').css({
	    left:leftVal,
	    top:topVal
	});
	$('#remindWrap').show();
	var s=s_gi('scrippsfood2');
	s.linkTrackVars='eVar1,events';
	s.linkTrackEvents='event41';
	s.eVar1='Challenge:' + challengeTitle;
	s.events='event41';
	s.tl(this,'o','email reminders');
	return false;
    });

    // Show "add a comment"
    $('a.addCommentLink').click(function(){
	$('#addCommentWrap').show();
	return false;
    });
	
    $('#anonsignout a').click(function(){
	$.cookie("anonName", null);
	$.cookie("anonEmail", null);
	$.cookie("anonSiteUrl", null);
	location.reload();
	return false;
    });
    // remove file upload
    $('a.uploadedfilename').click(function(){
	$(this).parent().hide();
	$('#assocMediaId').val('');
	$('#assocMediaType').val('');
	$('#assocMediaFileName').val('');
	$('#uploadField').show().val('');
	$('#uploadbutton1').show().val('Upload File');
	$('#commentUploadPanel p.helper').html('Upload an image from your computer.');
	return false;
    });

    // Closebox action
    $('.closeBox a').click(function(){
	$(this).parent().parent().parent().hide();
	return false;
    });

    $('#ugc-uploadwrap-inner .closeX').click(function(){
        ugctryagain();
	$(this).parent().parent().hide();
	return false;
    });

    $('.closeX').click(function(){
	$(this).parent().parent().hide();
	return false;
    });

    // Add review
    $('a.addReview').click(function(e){
	//getting height and width of the message box
	// var height = $('#ratingPopup').height();
	//var width = $('#ratingPopup').width();
	//calculating offset for displaying popup message
	//leftVal=e.pageX-(width/2)+"px";
	//topVal=e.pageY-(height/2)+"px";
	//assign the vals
	//$('#ratingPopup').css({left:leftVal,top:topVal})
	$('#ratingPopup').show();
	return false;
    });

    $('.addRecipeReview').click(function(){
	$('#addReview').show();
	return false;
    });

    function showAddReview(selectRadio) {
	$('#' + selectRadio).click();
	$('div#addReview').show();
	return false;
    }

    // Thoughts & Reviews Tabs
    /*
	$('#content-container h3.reviewtab a#turnedout').click(function(){
		$('h3.reviewtab a.active').removeClass('active');
		$(this).addClass('active');
		$('#recipeSuggestions, #recipeRemindsMe').hide();
		$('#recipeTurnedOut').show();
		$('#radioturnedout').click();
		return false;
	});
*/
    /*
	$('#content-container h3.reviewtab a#suggest').click(function(){
		$('h3.reviewtab a.active').removeClass('active');
		$(this).addClass('active');
		$('#recipeSuggestions').show();
		$('#recipeTurnedOut, #recipeRemindsMe').hide();
		$('#radiobetter').click();
		return false;
	});
*/
    
    // Tabs for upload / embed
    $('#commentTabs li a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	if (this.innerHTML == "Embed" || this.innerHTML == "Embed Code" || this.innerHTML == "Embed Video"){
	    $('#commentEmbedPanel').show();
	    $('#commentUploadPanel').hide();
	}else{
	    $('#commentUploadPanel').show();
	    $('#commentEmbedPanel').hide();
	}
	return false;
    });

    $('#recipeUploadTabs li a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	if (this.innerHTML == "Embed"){
	    $('#recipeEmbedPanel').show();
	    $('#recipeUploadPanel').hide();
	}else{
	    $('#recipeUploadPanel').show();
	    $('#recipeEmbedPanel').hide();
	}
	return false;
    });

    $('#challengeUploadTabs li a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	if (this.innerHTML == "Embed"){
	    $('#challengeEmbedPanel').show();
	    $('#challengeUploadPanel').hide();
	}else{
	    $('#challengeUploadPanel').show();
	    $('#challengeEmbedPanel').hide();
	}
	return false;
    });

    // Header Status Update

    $(document).click(function() {
	//Hide the menus if visible
	if (( $('#updateStatus').val() === '' ) || ($('#updateStatus').val() === 'is ') ) {
	    $('#updateStatus').val('is...');
	}
	$("#statusSelectContainer").css("display", "none");
    });

    $('#statusSelectContainer li a, #updateStatus').click(function(e){
	e.stopPropagation();
    });

    /*$('#updateStatus').blur(function(){
	if ((this.value === '') || (this.value === 'is ') ) {
	    $('#updateStatus').val('is...');	    
	}
	$("#statusSelectContainer").css("display", "none");
    });*/

    $('#updateStatus').bind("click", function(){
	$("#statusSelectContainer").css("display", "block");
    });

    $('#statusSelectContainer li a').each(function(){
	$(this).bind("click", function(){
	    $('#updateStatus').val($(this).text());
	    $("#statusSelectContainer").css("display", "none");
	    return false;
	//updateStatusProfile();
	});
    });

    // IE Cursor fix
    function cursorToEnd(iDofElem) {
	var gebi = document.getElementById(iDofElem);
	var endPos = (gebi.value.length)-1;
	if(gebi !== null) {
	    if(gebi.createTextRange) {
		var range = gebi.createTextRange();
		range.move('character', endPos);
		range.select();
	    }
	}
    }

    // Profile Actions
    $('#profile-updatestatus').focus(function(){
	$thisinput = $(this);
	if (this.value === 'is...'){
	    $thisinput.val('is surfing Food2.com in serious need of a snack');
	    if ($('.profilePostUpdate').length === 0) {
		$thisinput.after('<a href="javascript:void(0)" onclick="updateStatusProfile();" class="profilePostUpdate">Post Update</a>');
	    }
	    $thisinput.addClass('editingnow');
	    $('#statusupdate-hldr p').show();
	    $('#statusupdate-hldr p').show();
	    //$("#statusSelectContainer").css("display", "none");
	    var s=s_gi('scrippsfood2');
	    s.linkTrackVars='events';
	    s.linkTrackEvents='event15';
	    s.events='event15';
	    s.tl(this,'o','Post Update');
	    //todo matthew get actual value.length
	    cursorToEnd('profile-updatestatus');
	}
    })
    .blur(function(){
	$thisinput = $(this);
	if (this.value === 'is eating ' || this.value === '') {
	    $thisinput.val('is...');
	    $('a.profilePostUpdate').remove();
	    $thisinput.removeClass('editingnow');
	    $('#statusupdate-hldr p').hide();
	}
    });

    //Profile Tabs
    $('#uploadsTab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#favs').hide();$('#uploads').show();$('#aboutme').hide();$('#peeps').hide();
	$('#favsSort').attr("style", "display:none");
	$('#peepsSort').attr("style", "display:none");
	$('#uploadsSort').attr("style", "display:block");
	userAction.lastTabPushed="uploads";
	return false;
    });
    $('#aboutTab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#favs').hide();$('#aboutme').show();$('#uploads').hide();$('#peeps').hide();
	$('#favsSort').attr("style", "display:none");
	$('#peepsSort').attr("style", "display:none");
	$('#uploadsSort').attr("style", "display:none");
	userAction.lastTabPushed="about";
	return false;

    });
    $('#favsTab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#favs').show();$('#aboutme').hide();$('#uploads').hide();$('#peeps').hide();
	$('#favsSort').attr("style", "display:block");
	$('#peepsSort').attr("style", "display:none");
	$('#uploadsSort').attr("style", "display:none");
	userAction.lastTabPushed="favs";
	return false;

    });
    $('#peepsTab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#peeps').show();$('#aboutme').hide();$('#uploads').hide();$('#favs').hide();$('#peepsSort').show();
	$('#favsSort').attr("style", "display:none");
	$('#peepsSort').attr("style", "display:block");
	$('#uploadsSort').attr("style", "display:none");
	userAction.lastTabPushed="peeps";
	return false;
    });

    //Popular Post Tabs
    $('#populartab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#popularlist').show();
	$('#popularlist').attr("style", "display:block");
	$('#commentedlist').hide();
	$('#commentedlist').attr("style", "display:none");
	userAction.lastTabPushed="populartab";
	return false;
    });
    $('#commentedtab').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	$('#popularlist').hide();
	$('#popularlist').attr("style", "display:none");
	$('#commentedlist').show();
	$('#commentedlist').attr("style", "display:block");
	userAction.lastTabPushed="populartab";
	return false;
    });

    // show invite friends
    $('p.invite a').click(function(){
	$('#inviteFriends').toggle();
	return false;
    });

    $('p.invite_challenge a').click(function(){
	$('#inviteFriends').toggle();
	return false;
    });

    // Profile Edit Fields
    /* edits no longer inline
	$('a.profile-edit-btn').click(function(){
		$thisLink = $(this);
		$thisLink.parent().find('.profileText').hide();
		$thisLink.parent().find('.profileEdit').show();
		return false
	});

	$('.profile-cncl-edit').click(function(){
		$thisLink = $(this);
		$thisLink.parent().parent().find('.profileText').show();
		$thisLink.parent().parent().find('.profileEdit').hide();
		return false
	});
*/
    // Accordion (recipe list)
    $('#list1').show();
    $('#list1').accordion({
	header: '.accord'
    });
    //Accordion (FAQs)
    $('#faq-container').accordion({
	header: '.faq-hdr',
	autoHeight: false
    });

    //Accordion (tags for uploads)
    $('#categtree').accordion({
	header: '.categ-hdr',
	autoHeight: false
    });
    $('#categtree2').accordion({
	header: '.categ-hdr',
	autoHeight: false
    });

    // Video Dropdown Chicket
    //	$('li.item85').append('<a href="#" class="vdd">vdd</a>');

    // Video Dropdown Logic
    var leavelinktimer;
    var leavedropdowntimer;
    function vddLinkLeave(){
	leavelinktimer = setTimeout(function(){
	    $('#videoDropdown').hide();
	},300);
    }

    function vddLinkHover(){
	$('#videoDropdown').show();
    }

    function videoDropDownEnter(){
	clearTimeout(leavelinktimer);
    }

    function videoDropDownLeave() {
	leavedropdowntimer = setTimeout(function(){
	    $('#videoDropdown').hide();
	},300);
    }

    $('#mainnav-container .item85 a').hover(vddLinkHover).mouseleave(vddLinkLeave);
    $('#videoDropdown').mouseenter(videoDropDownEnter).mouseleave(videoDropDownLeave);


    // Recipe Dropdown Logic
    var leavelinktimer;
    var leavedropdowntimer;
    function rddLinkLeave(){
	leavelinktimer = setTimeout(function(){
	    $('#recipeDropdown').hide();
	},300);
    }

    function rddLinkHover(){
	$('#recipeDropdown').show();
    }

    function recipeDropDownEnter(){
	clearTimeout(leavelinktimer);
    }

    function recipeDropDownLeave() {
	leavedropdowntimer = setTimeout(function(){
	    $('#recipeDropdown').hide();
	},300);
    }

    $('#mainnav-container .item81 a').hover(rddLinkHover).mouseleave(rddLinkLeave);
    $('#recipeDropdown').mouseenter(recipeDropDownEnter).mouseleave(recipeDropDownLeave);


    // login dropdown Logic
    var leaveSigninLinkTimer;
    var leaveSigninDropdownTimer;
    function signinLinkLeave(){
	leaveSigninLinkTimer = setTimeout(function(){
	    $('#login-container').hide();
	},300);	
    }

    function signinLinkHover(){
	$('#login-container').show();
	clearTimeout(leaveSigninDropdownTimer);	
    }

    function signinDropDownEnter(){	
	clearTimeout(leaveSigninLinkTimer);
    }

    function signinDropDownLeave() {
	leaveSigninDropdownTimer = setTimeout(function(){
	    $('#login-container').hide();
	},300);	
    }

    $('#login-p a').hover(signinLinkHover).mouseleave(signinLinkLeave);
    $('#login-container').mouseenter(signinDropDownEnter).mouseleave(signinDropDownLeave);

    // category checkbox tree
    // prepend expander div
    $('#categtree li.unexp')
    .find('label:first').after('<span></span>');
    $('#categtree2 li.unexp')
    .find('label:first').after('<span></span>');

    // Check the parents when a child is clicked
    $("#categtree li.exp ul input:checkbox:checked").live('click', function(){
	var $this = $(this);
	if ( $this.parent().hasClass('exp') ){
	    $this.parents('li.exp:eq(1)')
	    .find('input:first')
	    .attr('checked','checked');
	}else{
	    $this.parents('li.exp').each(function(){
		$(this).find('input:first').attr('checked','checked');
	    });
	}
    });
    $("#categtree2 li.exp ul input:checkbox:checked").live('click', function(){
	var $this = $(this);
	if ( $this.parent().hasClass('exp') ){
	    $this.parents('li.exp:eq(1)')
	    .find('input:first')
	    .attr('checked','checked');
	}else{
	    $this.parents('li.exp').each(function(){
		$(this).find('input:first').attr('checked','checked');
	    });
	}
    });

    // Expand Collapse onclick
    $('#categtree li.unexp').find('span:first, label:first')
    .click(function(){
	var $label = $(this);
	if ( $label.parents('li:first').hasClass('unexp') ){
	    $label.parents('li:first').removeClass('unexp')
	    .addClass('exp');
	    $label.siblings('ul:first').show();
	}else{
	    $label.parents('li:first').removeClass('exp')
	    .addClass('unexp');
	    $label.siblings('ul:first').hide();
	}
    });
    $('#categtree2 li.unexp').find('span:first, label:first')
    .click(function(){
	var $label = $(this);
	if ( $label.parents('li:first').hasClass('unexp') ){
	    $label.parents('li:first').removeClass('unexp')
	    .addClass('exp');
	    $label.siblings('ul:first').show();
	}else{
	    $label.parents('li:first').removeClass('exp')
	    .addClass('unexp');
	    $label.siblings('ul:first').hide();
	}
    });

    // expand on check
    $('#categtree li.unexp input:checkbox, #categtree li.exp input:checkbox')
    .live('click',function(){
	var $checkbox = $(this);
	if ($checkbox.attr('checked')){
	    $checkbox.siblings('ul:first').show();
	    $checkbox.parents('li.unexp:first')
	    .removeClass('unexp')
	    .addClass('exp');
	}
    });
    $('#categtree2 li.unexp input:checkbox, #categtree2 li.exp input:checkbox')
    .live('click',function(){
	var $checkbox = $(this);
	if ($checkbox.attr('checked')){
	    $checkbox.siblings('ul:first').show();
	    $checkbox.parents('li.unexp:first')
	    .removeClass('unexp')
	    .addClass('exp');
	}
    });

    // Show Rating Popups
    $('.rateit').click(function(){
	$('#ratingPopup').show();
	return false;
    });

    // Show series Selector
    $('#seriesSelector').click(function(){
	$('#selectaserieswrap').show();
	return false;
    });

    // Settings Page
    $('#settingsnav ul li a').click(function(){
	$thislink = $(this);
	$thislink.parent().parent().find('li').removeClass('currentStep');
	$thislink.parent().addClass('currentStep');
	if (this.innerHTML == "My Notifications"){
	    $('#settingsWrap').hide();
	    $('#notificationwrap').show();
	}else{
	    $('#settingsWrap').show();
	    $('#notificationwrap').hide();
	}
    });

    // Popular Posts module
    $('#populartabs li a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	//alert(this.innerHTML);
	if (this.innerHTML == "Viewed"){
	    $('#popularlist').show();
	    $('.popularlist').show();
	    $('#commentedlist').hide();
	    $('.commentedlist').hide();
	}else{
	    $('#commentedlist').show();
	    $('#popularlist').hide();
	    $('.commentedlist').show();
	    $('.popularlist').hide();
	}
	return false;
    });

    // Stay in touch module
    $('#stayintouchtabs li a').click(function(){
	$thisLink = $(this);
	$thisLink.parent().parent().find('a').removeClass('active');
	$thisLink.addClass('active');
	if (this.innerHTML == "Get Food2"){
	    $('#getFood2').show();
	    $('#alerts').hide();
	}else{
	    $('#alerts').show();
	    $('#getFood2').hide();
	}
	return false;
    });

    // actions for facets
    $('a.showmorefacets').click(function(){
	$thisLink = $(this);
	$thisLink.parent().find('.moreFacets').show();
	return false;
    });

    // actions for video players
    $('#videoInfo').toggle(
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.showInfoPanel();
	    widget.hideSharePanel();
	    widget.hideEmailPanel();
	},
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.hideInfoPanel();
	}
	);

    $('#videoShare').toggle(
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.showSharePanel();
	    widget.hideInfoPanel();
	    widget.hideEmailPanel();
	},
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.hideSharePanel();
	}
	);

    $('#videoEmail').toggle(
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.showEmailPanel();
	    widget.hideSharePanel();
	    widget.hideInfoPanel();
	},
	function(){
	    var widget = navigator.appName.indexOf("Microsoft") != -1 ? window['food2VideoPlayer'] : document['food2VideoPlayer'];
	    widget.hideEmailPanel();
	}
	);
    // Comment Popup

    $('#commentPopup').jqm();
    $('#commentPopup').jqmAddClose('.closeMod');

    $('a.commentMedia').click(function(event){
        event.preventDefault();
	$lilcomment = $(this).parent().parent();
        $bigmedia = $lilcomment.find('.commentMediaLg').children().html();
        if($bigmedia == ''){
            $bigmedia = $lilcomment.find('.commentMediaLg').html();
        }
	$popauthor = $lilcomment.find('.usercommentImg').children().clone();
	$popinner = $lilcomment.find('.commentinner').children().clone();
	$popauthorlink = $lilcomment.find('.authorLink').children().clone();
	$('#commentpopMedia').html($bigmedia);
	$('#commentPopup .usercommentImg').html($popauthor);
	$('#commentPopup .commentinner').html($popinner);
	$('#commentPopup .authorLink').html($popauthorlink);
	setDartEnterpriseBanner2('BIGBOX', commentAd);
    });

    $('div.commentpopuptrigger').click(function(){
	$lilcomment = $(this).parent().parent();
        $bigmedia = $lilcomment.find('.commentMediaLg').children().html();
        if($bigmedia == ''){
            $bigmedia = $lilcomment.find('.commentMediaLg').html();
        }
	$popauthor = $lilcomment.find('.usercommentImg').children().clone();
	$popinner = $lilcomment.find('.commentinner').children().clone();
	$popauthorlink = $lilcomment.find('.authorLink').children().clone();
	$('#commentpopMedia').html($bigmedia);
	$('#commentPopup .usercommentImg').html($popauthor);
	$('#commentPopup .commentinner').html($popinner);
	$('#commentPopup .authorLink').html($popauthorlink);
	setDartEnterpriseBanner2('BIGBOX', commentAd);
    });

    /** Added for AJAX **/
    $('a.commentMedia').live('click', function(event){
        event.preventDefault();
	$lilcomment = $(this).parent().parent();
        $bigmedia = $lilcomment.find('.commentMediaLg').children().html();
        if($bigmedia == ''){
            $bigmedia = $lilcomment.find('.commentMediaLg').html();
        }
	$popauthor = $lilcomment.find('.usercommentImg').children().clone();
	$popinner = $lilcomment.find('.commentinner').children().clone();
	$popauthorlink = $lilcomment.find('.authorLink').children().clone();
	$('#commentpopMedia').html($bigmedia);
	$('#commentPopup .usercommentImg').html($popauthor);
	$('#commentPopup .commentinner').html($popinner);
	$('#commentPopup .authorLink').html($popauthorlink);
	setDartEnterpriseBanner2('BIGBOX', commentAd);
        $("#commentPopup").jqmShow();
    });

    $('div.commentpopuptrigger').live('click', function(){
	$lilcomment    = $(this).parent().parent();
        $bigmedia      = $lilcomment.find('.commentMediaLg').children().html();
        if($bigmedia == ''){
            $bigmedia = $lilcomment.find('.commentMediaLg').html();
        }
	$popauthor     = $lilcomment.find('.usercommentImg').children().clone();
	$popinner      = $lilcomment.find('.commentinner').children().clone();
	$popauthorlink = $lilcomment.find('.authorLink').children().clone();
	$('#commentpopMedia').html($bigmedia);
	$('#commentPopup .usercommentImg').html($popauthor);
	$('#commentPopup .commentinner').html($popinner);
	$('#commentPopup .authorLink').html($popauthorlink);
	setDartEnterpriseBanner2('BIGBOX', commentAd);
        $("#commentPopup").jqmShow();
    });

    // large image popup - tips
    $('.enlargerDiv').click(function(){
	$bigimg = $(this).next().attr('src');	
	if( $bigimg.indexOf("PHOTO_") ){
	   $bigimg = $bigimg.replace(/_\d+X\d*/img, "");
	}
	$('#popUpImg .popUpLgImg').attr('src', $bigimg);
    });



    // image popup
    $('#popUpImg').jqm({
	trigger: '.enlargerDiv', toTop: true
    });
    $('#popUpImg').jqmAddClose('.closeMod');
    $('#popUpImg').jqmAddClose('.closeButton');

    // login popup
    $('#mustlogin').jqm({
	trigger: '.logmein',
	toTop: true
    });


    $('#mustlogin').jqmAddClose('.closeMod');
    $('.logmein').click(function(e){

	action = this.getAttribute( "action" );
	$.cookie('login_action', action);

	
	var height = $('#mustlogin').height();
	var width = $('#mustlogin').width();
	var offset = $('#innerwrap').offset();
	var x = e.pageX - offset.left;
	var y = e.pageY - offset.top;
	/*console.log(x,y);
	leftVal=x-(width/2);
	topVal=y-(height/2);
	//assign the vals
	if ( topVal < -79 ){
	    topVal = -79;
	}
	topVal=topVal+"px";*/
	topVal='30%';
	/*if ( leftVal > 760 ){
	    leftVal = 760;
	}
	if ( leftVal < 0 ){
	    leftVal = 0;
	}
	leftVal=leftVal+"px";*/
	leftVal = '45%';
	$('#mustlogin').css({
	    left:leftVal,
	    top:topVal
	});
    });

    // Photo Gallery logic - NOT BEING USED
    $('#photoGallery').cycle({
	timeout:  0,
	speed: 0,
	pager:  '#galleryThumbs',
	prev: '#prevImage',
	next: '#nextImage',
	pagerAnchorBuilder: function(idx, slide) {
	    // return sel string for existing anchor
	    return '#galleryThumbs li:eq(' + (idx) + ') a';
	}
    });

    $('#challengeGallery').cycle({
	timeout:  0,
	speed: 0,
	pager:  '#galleryThumbs',
	pagerAnchorBuilder: function(idx, slide) {
	    // return sel string for existing anchor
	    return '#galleryThumbs li:eq(' + (idx) + ') a';
	}
    });

    // carousel

    /**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
    function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
	$('#gal-f-num').html(idx);
    }

    /**
 * This is the callback function which receives notification
 * when an item becomes the last one in the visible range.
 */
    function mycarousel_itemLastInCallback(carousel, item, idx, state) {
	$('#gal-l-num').html(idx);
    }

    /**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
    function mycarousel_initCallback(carousel) {
	jQuery('.jcarousel-control a').bind('click', function() {
	    carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
	    return false;
	});

	jQuery('.jcarousel-scroll select').bind('change', function() {
	    carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
	    return false;
	});

	jQuery('#nextth a').bind('click', function() {
	    carousel.next();
	    return false;
	});

	jQuery('#prevth a').bind('click', function() {
	    carousel.prev();
	    return false;
	});
    }


    // Ride the carousel...
    jQuery(document).ready(function() {
	jQuery("#galleryThumbsList").jcarousel({
	    scroll: 5,
	    initCallback: mycarousel_initCallback,
	    // This tells jCarousel NOT to autobuild prev/next buttons
	    buttonNextHTML: null,
	    buttonPrevHTML: null,
	    itemFirstInCallback:  mycarousel_itemFirstInCallback,
	    itemLastInCallback:   mycarousel_itemLastInCallback
	});
    });

    // upload field clear
    $('#prephour, #cookhour, #inprephour')
    .focus(function(){
	$this = $(this);
	if(this.value === 'hh'){
	    $(this).val('');
	}
    })
    .blur(function(){
	if(this.value === ''){
	    $(this).val('hh');
	}
    });

    $('#prepmins, #inprepmins, #cookmins')
    .focus(function(){
	$this = $(this);
	if(this.value === 'mm'){
	    $(this).val('');
	}
    })
    .blur(function(){
	if(this.value === ''){
	    $(this).val('mm');
	}
    });

    $(".printview").popupwindow();

    /* bookmark us */
    // add a "rel" attrib if Opera 7+
    if(window.opera) {
	if ($("a.jqbookmark").attr("rel") != ""){ // don't overwrite the rel attrib if already set
	    $("a.jqbookmark").attr("rel","sidebar");
	}
    }

    $("a.jqbookmark").click(function(event){
	event.preventDefault(); // prevent the anchor tag from sending the user off to the link
	var url = this.href;
	var title = this.title;

	if (window.sidebar) { // Mozilla Firefox Bookmark
	    window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
	    window.external.AddFavorite( url, title);
	} else if(window.opera) { // Opera 7+
	    return false; // do nothing - the rel="sidebar" should do the trick
	} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
	    alert('Unfortunately, this browser does not support the requested action,' + ' please bookmark this page manually.');
	}

    });

    $('#c-infopanel').click(function(){
	$('#challengeInfoPanel').toggle();
	return false;
    });

    // Gallery end panel tabs
    $('div.endframe').tabs();

 // Gallery UGC upload
    // show comment
    $('#ugcuploadset input').click(function(){
	$('#ugcphotodesc-set').show();
	$('#galleryugcsubmit').attr('disabled','').css({'color':'#F35D31','border': '1px solid #F35D31','cursor':'pointer'});
    })

    // limit chars in textarea
    $('#ugcphotodesc-set textarea[maxlength]').keyup(function(){
	var max = parseInt($(this).attr('maxlength'));
	    if($(this).val().length > max){
		$('.charsRemaining').addClass('toomany');
		$('#galleryugcsubmit').attr('disabled','disabled').css({'color':'#a4aeb7','border': '1px solid #a4aeb7','cursor':''});
	    }else{
		$('.charsRemaining').removeClass('toomany');
		$('#galleryugcsubmit').attr('disabled','').css({'color':'#F35D31','border': '1px solid #F35D31','cursor':'pointer'});
	    }
	$(this).parent().find('.charsRemaining').html((max - $(this).val().length));
    });

    // Show upload stuff
   $('#gallery-ugc-cta-wt-noimage').click(function(e){
        if($(this).attr('href') != "#"){ return false; }
        if($(this).hasClass('logmein')){ return false; }
	$('#ugc-uploadwrap').show();
	return false;
    });

   $('#gallery-ugc-cta-wt').click(function(e){
        if($(this).attr('href') != "#"){ return false; }
        if($(this).hasClass('logmein')){ return false; }
	$('#ugc-uploadwrap').show();
	return false;
    });

    $('#gallery-ugc-cta').click(function(){
        if($(this).hasClass('logmein')){ return false; }
	$('#ugc-uploadwrap').show();
	return false;
    });

    $('#ugc-uploadcancel').click(function(){
        ugctryagain();
	$('#ugc-uploadwrap').hide();
	return false;
    });

    // Challenge view panel tabs
    $('div#entryActionsPanel').tabs();

    $('#tweetThis a').click(function(){
	$('')
    });

}); // end of docReady

var z = 999;

/* FANCY DROPDOWNS GOES HERE */
// Fancy Dropdowns
checkExternalClick = function(event)
{
    if ($(event.target).parents('.activedropdown').length === 0)
    {
	$('.activedropdown').removeClass('activedropdown');
	$('.options').hide();
    }
};

$(document).ready(function()
{
    $(document).mousedown(checkExternalClick);

    /******************************************************************************************/
    $('select.fancy').each(function()
    {
	if(!$(this).parent().hasClass('enhanced'))
	{
	    targetselect = $(this);
	    targetselect.hide();

	    // set our target as the parent and mark as such
	    var target = targetselect.parent();
	    target.addClass('enhanced');

	    // prep the target for our new markup
	    target.append('<dl class="dropdown"><dt><a class="dropdown_toggle" href="#"></a></dt><dd><div class="options"><ul></ul></div></dd></dl>');
	    target.find('.dropdown').css('zIndex',z);
	    z--;

	    // we don't want to see it yet
	    target.find('.options').hide();

	    // parse all options within the select and set indices
	    var i = 0;
	    targetselect.find('option').each(function()
	    {
		// add the option
		target.find('.options ul').append('<li><a href="#"><span class="value">' + $(this).text() + '</span><span class="hidden index">' + i + '</span></a></li>');

		// check to see if this is what the default should be
		if($(this).attr('selected') == true)
		{
		    targetselect.parent().find('a.dropdown_toggle').append('<span></span>').find('span').text($(this).text());
		}
		i++;
	    });
	}
    });

    // let's hook our links, ya?
    $('a.dropdown_toggle').live('click', function()
    {
	var theseOptions = $(this).parent().parent().find('.options');
	if(theseOptions.css('display')=='block')
	{
	    $('.activedropdown').removeClass('activedropdown');
	    theseOptions.hide();
	}
	else
	{
	    theseOptions.parent().parent().addClass('activedropdown');
	    theseOptions.show();
	}
	return false;
    });

    // bind to clicking a new option value
    $('.options a').live('click', function(e)
    {
	$('.options').hide();
        
	var enhanced = $(this).parent().parent().parent().parent().parent().parent();
	var realselect = enhanced.find('select');

	// set the proper index
	realselect[0].selectedIndex = $(this).find('span.index').text();

	// update the pseudo selected element
	enhanced.find('.dropdown_toggle').empty().append('<span></span>').find('span').text($(this).find('span.value').text());
	resort( $(this).find('span.value').text());
	return false;
    });
    /******************************************************************************************/


    /******************************************************************************************/
    $('select.fancy3').each(function()
    {
	if(!$(this).parent().hasClass('enhanced'))
	{
	    targetselect = $(this);
	    targetselect.hide();

	    // set our target as the parent and mark as such
	    var target = targetselect.parent();
	    target.addClass('enhanced');

	    // prep the target for our new markup
	    target.append('<dl class="dropdown3"><dt><a class="dropdown_toggle3" href="#"></a></dt><dd><div class="options3"><ul></ul></div></dd></dl>');
	    target.find('.dropdown3').css('zIndex',z);
	    z--;

	    // we don't want to see it yet
	    target.find('.options3').hide();

	    // parse all options within the select and set indices
	    var i = 0;
	    targetselect.find('option').each(function()
	    {
		// add the option
		target.find('.options3 ul').append('<li><a href="#"><span class="value">' + $(this).text() + '</span><span class="hidden index">' + i + '</span></a></li>');

		// check to see if this is what the default should be
		if($(this).attr('selected') == true)
		{
		    targetselect.parent().find('a.dropdown_toggle3').append('<span></span>').find('span').text($(this).text());
		}
		i++;
	    });
	}
    });


    // let's hook our links, ya?
    $('a.dropdown_toggle3').live('click', function()
    {
	var theseOptions = $(this).parent().parent().find('.options3');
	if(theseOptions.css('display')=='block')
	{
	    $('.activedropdown3').removeClass('activedropdown3');
	    theseOptions.hide();
	}
	else
	{
	    theseOptions.parent().parent().addClass('activedropdown3');
	    theseOptions.show();
	}
	return false;
    });

    // bind to clicking a new option value
    $('.options3 a').live('click', function(e)
    {
	$('.options3').hide();

	var enhanced = $(this).parent().parent().parent().parent().parent().parent();
	var realselect = enhanced.find('select');

	// set the proper index
	realselect[0].selectedIndex = $(this).find('span.index').text();

	// update the pseudo selected element
	enhanced.find('.dropdown_toggle3').empty().append('<span></span>').find('span').text($(this).find('span.value').text());
	resort2( $(this).find('span.value').text());
	return false;
    });
    /******************************************************************************************/

    /******************************************************************************************/
    /* DV */ // blog module sort
    $('select.fancy2').each(function()
    {
	if(!$(this).parent().hasClass('enhanced'))
	{
	    targetselect = $(this);
	    targetselect.hide();

	    // set our target as the parent and mark as such
	    var target = targetselect.parent();
	    target.addClass('enhanced');

	    // prep the target for our new markup
	    target.append('<dl class="dropdown"><dt><a class="dropdown_toggle2" href="#"></a></dt><dd><div class="options2"><ul></ul></div></dd></dl>');
	    target.find('.dropdown').css('zIndex',z);
	    z--;

	    // we don't want to see it yet
	    target.find('.options2').hide();

	    // parse all options within the select and set indices
	    var i = 0;
	    targetselect.find('option').each(function()
	    {
		// add the option
		target.find('.options2 ul').append('<li><a href="#"><span class="value">' + $(this).text() + '</span><span class="hidden index">' + i + '</span></a></li>');

		// check to see if this is what the default should be
		if($(this).attr('selected') == true)
		{
		    targetselect.parent().find('a.dropdown_toggle2').append('<span id="toggle2"></span>').find('span').text($(this).text());
		}
		i++;
	    });
	}
    });


    // let's hook our links, ya?
    $('a.dropdown_toggle2').live('click', function()
    {
	var theseOptions = $(this).parent().parent().find('.options2');
	if(theseOptions.css('display')=='block')
	{
	    $('.activedropdown').removeClass('activedropdown');
	    theseOptions.hide();
	}
	else
	{
	    theseOptions.parent().parent().addClass('activedropdown');
	    theseOptions.show();
	}
	return false;
    });

    // bind to clicking a new option value
    $('.options2 a').live('click', function(e)
    {
	$('.options2').hide();

	var enhanced = $(this).parent().parent().parent().parent().parent().parent();
	var realselect = enhanced.find('select');

	// set the proper index
	realselect[0].selectedIndex = $(this).find('span.index').text();

	// update the pseudo selected element
	enhanced.find('.dropdown_toggle2').empty().append('<span id="toggle2"></span>').find('span').text($(this).find('span.value').text());
	resort( $(this).find('span.value').text());
	return false;
    });
    /* DV */ /*blog module sort -- end */
    /******************************************************************************************/

});

function resort() {

    if ( $('#sortby').val() == "Most Relevant" || $('.dropdown_toggle span').html() == "Most Relevant" && window.location.href.indexOf("/profile/") < 1 ) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=relevant&action=sort";
	window.location.href=newquery;

    } else if ( $('#sortby').val() == "Most Recent"  || $('.dropdown_toggle span').html() == "Most Recent" && window.location.href.indexOf("/profile/") < 1 && window.location.href.indexOf("blog") < 1 ) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=recent&action=sort";
	window.location.href=newquery;
			  
    } else if ($('#sortby').val() == "Rating"  || $('.dropdown_toggle span').html() == "Rating"  && window.location.href.indexOf("profile") < 1 ) {

	var query = window.location.search.substring(1);
	var vars = query.split("&");
	//alert(vars[1]);
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=rating&action=sort";
	window.location.href=newquery;

    } else if ($('#sortby').val() == "Cook Time"  || $('.dropdown_toggle span').html() == "Cook Time") {

	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=cooktime&action=sort";
	window.location.href=newquery;

    } else if ($('#favsSort').css('display')=='block'){

	if($('#favsSort').val() == "Most Recent"  || $('#favsSort .dropdown_toggle span').html() == "Most Recent") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostRecent&action=sort&t=f";
	    window.location.href=newquery;

	} else if($('#favsSort').val() == "Most Viewed"  || $('#favsSort .dropdown_toggle span').html() == "Most Viewed") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostViewed&action=sort&t=f";
	    window.location.href=newquery;

	} else if($('#favsSort').val() == "Most Discussed"  || $('#favsSort .dropdown_toggle span').html() == "Most Discussed") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostDiscussed&action=sort&t=f";
	    window.location.href=newquery;
	}

    } else if ($('#peepsSort').css('display')=='block'){

	if ($('#peepsSort').val() == "Alphabetical"  || $('#peepsSort .dropdown_toggle span').html() == "Alphabetical") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=alpha&t=p";
	    window.location.href=newquery;

	} else if($('#peepsSort').val() == "Most Uploads"  || $('#peepsSort .dropdown_toggle span').html() == "Most Uploads") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostuploads&t=p";
	    window.location.href=newquery;

	} else if($('#peepsSort').val() == "Most Recent"  || $('#peepsSort .dropdown_toggle span').html() == "Most Recent") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2)!= "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=recent&t=p";
	    window.location.href=newquery;
	}
    } else if ($('#uploadsSort').css('display')=='block'){

	if($('#uploadsSort').val() == "Most Recent"  || $('#uploadsSort .dropdown_toggle span').html() == "Most Recent") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostRecent&action=sort&t=u";
	    window.location.href=newquery;

	} else if($('#uploadsSort').val() == "Most Viewed"  || $('#uploadsSort .dropdown_toggle span').html() == "Most Viewed") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostViewed&action=sort&t=u";
	    window.location.href=newquery;

	} else if($('#uploadsSort').val() == "Most Discussed"  || $('#uploadsSort .dropdown_toggle span').html() == "Most Discussed") {
	    var query = window.location.search.substring(1);
	    var vars = query.split("&");
	    var newquery = "?";
	    for (var i=0;i<vars.length;i++) {
		var j = vars[i];
		if (j.substring(0,11) != "sort_order=" && j != "" && j != "action=sort" && j.substring(0,2) != "t=") {
		    newquery += vars[i]+"&";
		}
	    }
	    newquery+="sort_order=mostDiscussed&action=sort&t=u";
	    window.location.href=newquery;

	}

    /* DV */ /* Challenges in 'voting' phase */
    } else if ($('#sortby').val() == "Recently Rated"  || $('.dropdown_toggle span').html() == "Recently Rated") {

	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=recentlyrated&action=sort";
	window.location.href=newquery;

    } else if ($('#sortby').val() == "Most Votes"  || $('.dropdown_toggle span').html() == "Most Votes") {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=mostvotes&action=sort";
	window.location.href=newquery;


    /* DV */ /* Challenges in 'over' phase */
    } else if ($('#sortby').val() == "Most Viewed"  || $('.dropdown_toggle span').html() == "Most Viewed") {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	//alert(vars[1]);
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=mostviewed&action=sort";
	window.location.href=newquery;

    } else if ($('#sortby').val() == "Most Discussed"  || $('.dropdown_toggle span').html() == "Most Discussed") {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=mostdiscussed&action=sort";
	window.location.href=newquery;

    } else if ($('#sortby').val() == "Most Shared"  || $('.dropdown_toggle span').html() == "Most Shared") {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	//alert(vars[1]);
	var newquery = "?";
	for (var i=0;i<vars.length;i++) {
	    var j = vars[i];
	    if (j.substring(0,5) != "sort=" && j != "" && j != "action=sort") {
		newquery += vars[i]+"&";
	    }
	}
	newquery+="sort=mostshared&action=sort";
	window.location.href=newquery;

    } else if ( $('#sortby select').hasClass('blogger') ){
	var blogValue = $('#sortby option:selected').val();
	var url = window.location.href='index.php?option=com_blogs&view=list&Itemid=82&members=' + blogValue;

    }
}

function resort2() {
    if ( $('#sortby select').hasClass('popularblog') ){
	if ( $('#sortby').val() == "Commented"  || $('.dropdown_toggle3 span').html() == "Commented" && window.location.href.indexOf("blog") > 1 && $('#sortby select').hasClass('popularblog') ) {
	    $('#commentedlist').show();
	    $('#popularlist').hide();
	    $('.commentedlist').show();
	    $('.popularlist').hide();
	    $('li.mostpopulartab a.active').removeClass('active');
	    $('li.mostcommentedtab a.active').addClass('active');
	    $('span#toggle2').html("Commented");
	} else if ( $('#sortby').val() == "Viewed"  || $('.dropdown_toggle3 span').html() == "Viewed" && window.location.href.indexOf("blog") > 1  ) {
	    $('#commentedlist').hide();
	    $('#popularlist').show();
	    $('.commentedlist').hide();
	    $('.popularlist').show();
	    $('li.mostpopulartab a.active').addClass('active');
	    $('li.mostcommentedtab a.active').removeClass('active');
	    $('span#toggle2').html("Viewed");
			
	}
    }
}

function emailed(resp) {
    $('#emailFriendsContainer fieldset').html('<h3>Your email was sent!</h3>');
}

function flagComment(mediaId, mediaType, url, commentId, token, message, thislink) {
    $this = $(thislink);
    if (message == null || message == "") {
	message = "Inappropriate comment";
    }

    var request = 'http://api.kickapps.com/rest/flagcomment/' + commentId + '/' + mediaType + '/' + mediaId + '/94312?t=' + token + "&";
    request += "callback=flaggedComment&url=" + encodeURIComponent(url) + "&message=" + message;
    aObj = new JSONscriptRequest(request);
    aObj.buildScriptTag();
    aObj.addScriptTag();
    $this.parent().html('<span style="color: #ff0000; font-weight: bold;">Flagged! (<a href="#" onclick="unFlagComment(\''+mediaId+'\', \''+mediaType+'\', \''+url+'\', \''+commentId+'\', \''+token+'\', \''+message+'\', this); return false;">Undo</a>)</span>');
    return false;
}

function flagEntry(mediaId, mediaType, url, commentId, token, message, thislink, ip, editLink) {
    $this = $(thislink);
    if (message == null || message == "") {
	message = "Inappropriate entry";
    }

    var request = 'http://api.kickapps.com/rest/flag/add/emedia/1234/94312?t=' + token + "&";
    request += "callback=flaggedComment&ip=" + ip + "&url=" + encodeURIComponent(url) + "&message=" + message;
    aObj = new JSONscriptRequest(request);
    aObj.buildScriptTag();
    aObj.addScriptTag();
    if(editLink == ""){
        $this.parent().html('<span style="color: grey; font-weight: bold;">Flagged (<a href="#" onclick="unFlagEntry(\''+mediaId+'\', \''+mediaType+'\', \''+url+'\', \''+commentId+'\', \''+token+'\', \''+message+'\', this, \''+ip+'\'); return false;">Undo</a>)</span>');
    }
    return false;
}

function unFlagEntry(mediaId, mediaType, url, commentId, token, message, thislink, ip) {
    $this = $(thislink);
    $this.parent().html('<span><a href="#" onclick="flagEntry(\''+mediaId+'\', \''+mediaType+'\', \''+url+'\', \''+commentId+'\', \''+token+'\', \''+message+'\', this, \''+ip+'\'); return false;">Flag</a></span>');
    return false;
}

function unFlagComment(mediaId, mediaType, url, commentId, token, message, thislink, ip) {
    $this = $(thislink);
    $this.parent().html('<span><a href="#" onclick="flagComment(\''+mediaId+'\', \''+mediaType+'\', \''+url+'\', \''+commentId+'\', \''+token+'\', \''+message+'\', this); return false;">Flag</a></span>');
    return false;
}

function flaggedComment() {
    return false;
}

function videoLeaveComment() {
    $('#commentAnchor').ScrollTo(100);
    $('#addCommentWrap').show();
}


// chat button

// IF AGENTS ARE AVAILABLE:
function agents_available()
{
    $('#agentavailable').show();
    $('#noagent').hide();
    return true;
}
// IF AGENTS ARE NOT AVAILABLE:
function agents_not_available()
{
    $('#agentavailable').hide();
    $('#noagent').show();
    return true;
}

function addslashes(str) {
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\0/g,'\\0');
    return str;
}
function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\0/g,'\0');
    str=str.replace(/\\\\/g,'\\');
    return str;
}

function ugctryagain() {
    $('#ugcuploadset, #ugcphotodesc-set').show();
    $('#ugc-isuploading').hide();
    $('#ugcphotodesc-set').hide();
    $('#submitorcancel').html('<input type="submit" value="Upload" id="galleryugcsubmit" disabled="disabled" /> or <a href="#" id="cancelugcupload" onclick="closeugcuploads(); return false;">Cancel</a>');
    return false;
}

function closeugcuploads(){
    $('#ugc-uploadwrap').hide();
    ugctryagain();
    return false;
}

Date.prototype.formatDate = function(format) {
    var date = this;
    if (!format)
      format="MM/dd/yyyy";

    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    format = format.replace("MM",month.toString().padL(2,"0"));

    if (format.indexOf("yyyy") > -1)
        format = format.replace("yyyy",year.toString());
    else if (format.indexOf("yy") > -1)
        format = format.replace("yy",year.toString().substr(2,2));

    format = format.replace("dd",date.getDate().toString().padL(2,"0"));

    var hours = date.getHours();

    if (format.indexOf("t") > -1) {
       if (hours > 11)
        format = format.replace("t","pm")
       else
        format = format.replace("t","am")
    }

    if (format.indexOf("HH") > -1)
        format = format.replace("HH",hours.toString().padL(2,"0"));

    if (format.indexOf("hh") > -1) {
        if (hours > 12){ hours = (hours - 12); }
        if (hours == 0){ hours = 12; }
        format = format.replace("hh",hours.toString().padL(2,"0"));
    }

    if (format.indexOf("mm") > -1)

       format = format.replace("mm",date.getMinutes().toString().padL(2,"0"));

    if (format.indexOf("ss") > -1)

       format = format.replace("ss",date.getSeconds().toString().padL(2,"0"));

    return format;

}

String.repeat = function(chr,count) {
    var str = "";
    for(var x=0;x<count;x++) {str += chr};
    return str;
}

String.prototype.padL = function(width,pad) {
    if (!width ||width<1)
        return this;


    if (!pad) pad=" ";
        var length = width - this.length

    if (length < 1) return this.substr(0,width);


    return (String.repeat(pad,length) + this).substr(0,width);
}

String.prototype.padR = function(width,pad) {

    if (!width || width<1)

        return this;


    if (!pad) pad=" ";
    var length = width - this.length
    if (length < 1) this.substr(0,width);


    return (this + String.repeat(pad,length)).substr(0,width);
}

String.format = function(frmt,args) {
    for(var x=0; x<arguments.length; x++){
        frmt = frmt.replace("{" + x + "}",arguments[x+1]);
    }
    return frmt;
}


function changeSize(url, newSize) {
    var result;
    if(typeof url != 'undefined'){
        if (url.match(/_main_(.*)/im)) {
            result = url.replace(/_main_(.*)/img, "_main_"+newSize.toUpperCase()+".jpg");
        } else {
            result = url.replace(/_main\./img, "_main_"+newSize.toUpperCase()+".");
        }
    }
    return result;
}


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}