var SLIDE_SPEED = 500

function jeval(str){return eval('(' +  str + ');'); }

//tog
function tog(clicker, toggler, callback, speed){
  if (speed == undefined)
    speed = SLIDE_SPEED;
  if (callback)
    jQuery(clicker).click(function(){jQuery(toggler).slideToggle(speed, callback); return false;});
  else
    jQuery(clicker).click(function(){jQuery(toggler).slideToggle(speed); return false;});
}

function togger(j, callback, speed){
  if (speed == undefined)
    speed = SLIDE_SPEED;
  if(callback)
  jq(j).slideToggle(speed, callback); 
  else 
  jq(j).slideToggle(speed); 
}
//tog

//message
function async_message(m, d){message(m, d);}
function messages(m, d){message(m, d);}
function message(message, duration){
    if (duration == undefined){
        duration = 3000;
    }
    if (jq.browser.msie) { jq("#message").css({position: 'absolute'}); }
    $("message").innerHTML = message;
    jq("#message").fadeIn(1000);

    setTimeout('jq("#message").fadeOut(2000)',duration);
    return false;
}
//message
function debug(m){if (typeof console != 'undefined'){console.log(m);}}
function puts(m){debug(m);}

function thickbox(id, title, height, width){
//    location.href = '/photos/' + id;
//    return;

    if (height == undefined){ height = 300}
    if (width == undefined){ width = 300}
    tb_show(title, '#TB_inline?height='+ height +'&amp;width='+ width +'&amp;inlineId='+ id +'', false);
    return false;
}
function truncate(str, len){
    if (len == undefined){len = 9}
    
    if (str.length <= len+3){return str;}
    
    return str.substring(0, len) + '...'
}

function tog_login_element() {
	jq('.login_element, .checkout_element').toggle();
}

//start up
jq(function(){
    initCalendarControls();
    
  	//waiter
  	jQuery("#waiter").ajaxStart(function(){jq(this).show();}).ajaxStop(function(){jq(this).hide();}).ajaxError(function(){jq(this).hide();});

	jq('.jstruncate').truncate({max_length: 50});
	
	jq('#search_q').bind('focus.search_query_field', function(){
		if(jq(this).val() == 'Search for Friends'){
			jq(this).val('');
		}
	});
	
	jq('#search_q').bind('blur.search_query_field', function(){
		if(jq(this).val()==''){
			jq(this).val('Search for Friends');
		}
	});

	jq('.search_friends').bind('focus.search_query_field', function(){
		if(jq(this).val()=='Search for workouts'){
			jq(this).val('');
		}
	});

	jq('.search_friends').bind('blur.search_query_field', function(){
		if(jq(this).val()==''){
			jq(this).val('Search for workouts');
		}
	});

	jq('.user_workout_search').bind('focus.search_query_field', function(){
		if(jq(this).val()=='Search for User Workouts'){
			jq(this).val('');
		}
	});

	jq('.user_workout_search').bind('blur.search_query_field', function(){
		if(jq(this).val()==''){
			jq(this).val('Search for User Workouts');
		}
	});

//	jq(".remote_form input[type='submit'].button").bind('click', function(){
//        this.disabled = true;
//        jq(this).after('<img id="loading_spinner" src="/images/spinner_2.gif" alt="loading" style="margin-left:10pxl"/>');
////        this.style.display = 'none';
//	});

    jQuery(document).ready(function() {
            jq("#heroku_toolbar").each(function(i) {this.style.display = 'none';});        
            jq("a.fancybox").each(function(i) {
                     jq(this).fancybox({
                        frameHeight : this.getAttribute("fancy_height"),
                        zoomSpeedIn : 500,
                        hideOnContentClick : false,
                        overlayShow :true,
                        overlayOpacity : .6
                    });
                  });

     });

});
//start up

function toggleComments(comment_id)
{
	jq('#comment_'+comment_id+'_short, #comment_'+comment_id+'_complete').toggleClass('hidden');
  
	jq('#comment_'+comment_id+'_toggle_link').html(
    	jq('#comment_'+comment_id+'_toggle_link').html() == "(more)" ? "(less)" : "(more)"
	); 
}

function showDateRange(parent) {
//    new Effect.BlindDown($('date_range_picker'));
//    $('date_range_picker').style.left = Element.positionedOffset(parent)[0] + 'px';
   jQuery('#date_range_picker').slideToggle(200);
}
function hideDateRange() {
//    new Effect.BlindUp($('date_range_picker'));
    jQuery('#date_range_picker').hide();
}

function showBenchmarkPicker(parent) {
    showPicker('#benchmark_picker', parent);
}

function hideBenchmarkPicker() {
    hidePicker('#benchmark_picker');
}

function showFriendPicker(parent) {
    showPicker('#friend_picker', parent);
}

function hideFriendPicker() {
    hidePicker('#friend_picker');
}

function showPicker(id,parent) {
    //jQuery(id).style.left = Element.positionedOffset(parent)[0] + 'px';
    jQuery(id).slideToggle(200);
}

function hidePicker(id) {
    jQuery(id).hide();
}

function showCleanPicker(id,parent) {
    //$(id).style.left = Element.positionedOffset(parent)[0] + 'px';
    jQuery(".clean_picker:not(#" + id + ")").hide();
    jQuery("#" + id).slideToggle(200)
    jQuery("#" + id).prev('.picker_control').toggleClass('clean_picker_open');
}


function hideCleanPicker(id) {
    jQuery("#" + id).slideToggle(200);
    jQuery("#" + id).prev('.picker_control').toggleClass('clean_picker_open');
}

function closeFancyBox() {
    jq('#fancy_link').fancybox.close();
}

function resetRemoteForm(r) {
    jq(".remote_form input[type='submit'].button").each(function(){
        this.disabled = false;
        $("loading_spinner").remove();
    });
}

function disableRemoteButtons(r) {
    jq(".remote_form input[type='submit'].button").each(function(){
        $(this).disabled = true;
        jq(this).after('<img id="loading_spinner" src="/images/spinner_2.gif" alt="loading" style="margin-left:10pxl"/>');
    });
}

//reloads the list of user workouts on the my worklouts screen for the date range
function reload_user_workouts() {
   range = $('selected_date_range').innerHTML;
   new Ajax.Request('/user_workouts/reload_user_workouts?range=' + range,
           {asynchronous:true, evalScripts:true});
        return false;
}

function toggleTwitterControls(enabled) {
    $('profile_twitter_login').disabled = !enabled;
    $('twitter_password').disabled = !enabled;
}

function show_loading(elem) {
    jq(elem).after('<img id="loading_spinner" src="/images/spinner_2.gif" alt="loading" style="margin-left:10pxl"/>');
}

function toggleCalendarRepeatFrequency(visible) {
    if (visible == 'true') {
        $('#repeat_frequency').fadeIn();
    }else {
        $('#repeat_frequency').fadeOut();
    }
}

function toggleWorkoutEntry(elem) {
    if (elem == 'existing_workout') {
            $('#existing_workout').show();
            $('#custom_workout').hide();
            $('#height_holder').hide();
     }else{
        $('#existing_workout').hide();
        $('#custom_workout').show();
        $('#height_holder').hide();
    }

 }

function initCalendarControls() {
    jQuery(".datepicker").datepicker({
            showOn: 'button',
            buttonImage: '/images/calendar.gif',
            buttonImageOnly: true
            });
}

function initColorSwabPicker() {
    jQuery("ul.color_picker li a").click(function (){
        jQuery('#gym_class_css_color_class').val(this.id);
        jQuery('ul.color_picker li').removeClass('selected');
        jQuery(this).parent().addClass('selected');
    });
}

function initWorkoutAutocomplete() {
    jQuery("#workout_autocomplete").autocomplete({
        source: "/workouts/auto_complete_for_workout_name",
        minLength: 3,
        select: function(event, ui) {
            jQuery('#wod_workout_id').val(ui.item.id);
        }
    });
}

function initUserFinderAutocomplete() {
    jQuery("#user_autocomplete").autocomplete({    
        source: "/users/auto_complete_for_name",
        minLength: 3,
        focus: function(event, ui) {
            jQuery('#calendar_event_submit').attr("disabled", true);
        },
        select: function(event, ui) {
            jQuery('#user_id').val(ui.item.id);
            jQuery('#calendar_event_submit').val('Check-in as ' +ui.item.value) ;
            jQuery('#calendar_event_submit').attr("disabled", false);
        }
    });
}


function reloadCalendar() {
    jQuery('#gym_calendar').fullCalendar('refetchEvents');
}

function initWysiwyg(elementExpression) {
    jQuery(elementExpression).wysiwyg({css: "/stylesheets/blueprint/screen.css",
                                  formImageHtml: '<fieldset><legend>Insert Image</legend><div class="upload_error" style="display:none"></div><form action="/upload_forum_image.js" id="upload_forum_image" target="upload_frame" method="post" enctype="multipart/form-data" ><label for="photo_image">Image: </label><input name="image" size="15" type="file" /> <div class="clear"></div><div class="row button"><input class="button"  name="commit" type="submit" value="Upload Photo" /></div></form></fieldset>'
                                  });


}

//Setup the calcuations for load based workouts where its many rounds like 3 3 3 3 3

function initializeLoadBasedFieldListener(){
        jQuery.Calculation.setDefaults({
            onParseError: function(){
                this.css("backgroundColor", "#e2f9e3")
            }
            , onParseClear: function (){
                this.css("backgroundColor", "");
            }
        });

    // automatically update the "#totalSum" field every time
    // the values are changes via the keyup event
    jQuery(".load_variable").sum("keyup", "#total_sum");
    jQuery(".load_variable").keyup(function() {
          jQuery('#workout_note').text(jQuery('#workout_note').text()  + this.value + ' ');
        });

}