jQuery(document).ready( function() {
	
	// is IE?
	var isIE = ($.browser.msie) ? "isIE":"";
	
	// instantiate any character counters
	$('*[counter]').each( function() { $(this).counter( 155, true ); });
	
	// if ( !isIE ) {
		// corners on tab nav
		$('#tab_nav ul li').corner({
			tl: { radius: 16 },
			tr: { radius: 16 },
			bl: false,
			br: false,
			antiAlias: true,
			autoPad: false
		});
		

	// }

	// tab nav hovers
	$('ul#tab_nav li').hover(function() {
		$(this).addClass('navHover');
	}, function() {
		$(this).removeClass('navHover');
	});
	
	set_tab();
	
	$('#bubble_stem').css('left', ($('#nav li a.active').offset().left - 45) + "px");
	
	/* flash fonts for prettiness */
	// if(typeof sIFR == "function"){
	// 	sIFR.setup();
	// 	//sIFR.debug();
	// };
	// sIFR.activate();
	// sIFR.replace(headerFont, sIFR_admin_h1s);
	// sIFR.replace(headerFont, huge_sIFR_h1s);
	// sIFR.replace(headerFont, sIFR_h1s);
	// sIFR.replace(headerFont, sIFR_admin_h2s);
	// sIFR.replace(headerFont, sIFR_h2s);
	
	$('img.help').mouseover( function() {
		tooltip( $(this), $(this).attr('alt') );
	});
	
	$(":text, :password").labelify();
	
});

function showLoader() {
	var x = ($(window).width()/2) - 65;
	$('#loader').css('left', x+'px' );
	$('#loader').animate({ bottom: "-15px" }, 200);
}

function hideLoader() {
	$('#loader').animate({ bottom: "-65px" }, 200);
}

/* custom tooltip functions */

// remove the tooltip
function tooltip_kill(obj) {
	var msg = $('#tooltip').html();
	$('#tooltip').remove();
	if (msg) $(obj).attr('alt', msg);
}

// create the tooltip.
// obj: element to palce the tooltip near.  use CSS declarations, like "#header"
// msg: what the tooltip should say.  escaped HTML is fine.
// killEvent: jQuery event to remove the tooltip, like "click", "mouseover", etc.
// offX: horizontal offset, in pixels
// offY: vertical offset, in pixels
// left_right:  position using either CSS property "left" or "right"
function tooltip(obj, msg, killEvent, offX, offY, left_right) {
	
	if (!left_right) left_right = "left";
	if (!offX) offX = 20;
	if (!offY) offY = 0;
	
	if (obj) {
		tooltip_kill(obj);
		var offset = $(obj).offset();
		var tooltip_html = "<div id='tooltip' style='top:"+eval(offset.top+offY)+"px;"+left_right+":"+eval(offset.left+offX)+"px;'>";
		tooltip_html += unescape(msg);
		tooltip_html += "</div>";
		$('body').append(tooltip_html);
		$(obj).attr('alt','');
		if (!killEvent) $(obj).mouseout(function() { tooltip_kill(obj); } );
			else $(obj).bind(killEvent, function() { tooltip_kill(obj); } );
	}
}

function set_tab( id ) {
	if ( $('#tab_nav ul').length > 0 && $('#tab_nav ul').css('display') != "none" ) {
		if ( window.location.hash && window.location.hash.indexOf('tab=') != -1 ) {
			id = window.location.hash.substr( window.location.hash.indexOf('tab=')+4 );
		}
		if ( typeof id != 'undefined' ) {
			$('#tab_nav ul li').each( function() { $(this).removeClass('active'); } );
			$('#'+id).addClass('active');
		}
		$('#bubble_stem').hide(0);
	}
}

function setTopNav( which ) {
	$('#nav li a').removeClass('active');
	$('#nav_'+which).addClass('active');
	$('#bubble_stem').css('left', ($('#nav_'+which).offset().left - 65) + "px");
}

/* form validation */
// validates that any input or textarea with class "required" is not empty
// if it is, it makes that field red, and tacks on an error message at the end of the form
// fires on blur of each required field
function activate_form_fields( id, action ) {
	// ie stinks.
	// $('#'+id+' [type=submit]' ).attr('disabled','');
	// return true;
	
	// var valid_form = true;
	$('#'+id+' *[required]' ).each( function() {
		if ( $(this).val().length > 0 ) $(this).addClass('check');
		$(this).blur( function() {
			$(this).addClass('check');

			if ( $(this).val() == "" ) {
				$(this).addClass('error');
				$(this).removeClass('valid');
				// console.log('error');
			} else {
				// valid_form = true;
				$(this).removeClass('error');
				$(this).addClass('valid');
							// console.log('valid');
			}
			validate_form_fields( id );
		});
		
		// if this is a pre-filled form, it might validate already.  check it once, if "Edit" is passed in.
		// using "Edit" since that is the predefined action in PHP on many forms.
		if ( action == "Edit" ) {
			$(this).addClass('check');
			if ( $(this).val() == "" ) {
				$(this).addClass('error');
				$(this).removeClass('valid');
				// console.log('load error');
			} else {
				// valid_form = true;
				$(this).removeClass('error');
				$(this).addClass('valid');
				// console.log('load valid');
			}
			validate_form_fields( id );
		}
	});

	if ( $('#'+id+' *[required]' ).length == 0 ) $('#'+id+' [type=submit]' ).attr('disabled','');

}

function validate_form_fields( id ) {
	// console.log(1111);
	var valid_form = false;
	
	// using set CSS classes from activate_form_fields() to determine if required fields have content
	// can then easily add checks in activate_form_fields() for other types of validation
	// which we'll do using custom attributes, like <input type="text" class="required" required="length:10" /> etc
	var disabled_fields =  $('#'+id+' *[disabled][required]').length;
	// console.log($('#'+id+' *[required]').length + " :: check:" + $('#'+id+' *[required].check').length + " :: disabled:" + disabled_fields);
	// console.log($('#'+id+' *[required]').length + " :: valid:" + $('#'+id+' *[required]').length + " :: disabled:" + disabled_fields);
	if (
		( $('#'+id+' *[required]').length == $('#'+id+' *[required].check').length ) &&
		( $('#'+id+' *[required]').length == $('#'+id+' *[required].valid').length )
	   ) {
		valid_form = true; 
			// console.log(22222);
	}
	
	// too many chars?
	$('#'+id+' *[required="group_length"]').each( function() {
		var group = $(this).attr('name').substr(4);
		var total_cur = parseInt( $('#'+group+'_msg .total_chars').text() );
		if ( total_cur > parseInt($(this).attr('max')) ) {
			valid_form = false;
		}
	});

	// if ( valid_form == true ) $('#'+id+' input[type="submit"]').attr('disabled', false);
		// else $('#'+id+' input[type="submit"]').attr('disabled', true);
	
	// if ( $('#'+id+' input[type="submit"]').attr('disabled') && show_form_error ) {
	// 	if ( $('#error_'+id).length == 0 ) $('#'+id+' input[type="submit"]').after( '<div id="error_'+id+'" class="error hidden">You have some required fields that have errors, or are empty.</div>' );
	// 	$('#error_'+id).show(200);
	// } else 
	// $('#error_'+id).hide(200);
}

// add poll questions to create campaign field
function addPollQuestion() {
	var q_id = Number(document.getElementById("q_id").value);
	$("#questions").append("<div id='question"+q_id+"' style='margin-bottom: 20px; opacity:0;'><hr/><h3>Poll Question</h3>"+
		"<textarea name='Questions["+q_id+"]' id='question_text"+q_id+"' cols='30' rows='3' counter='poll_"+q_id+"_chars'></textarea>" +
		"<br/><a href='#' onClick='removePollQuestion("+q_id+"); return false;'>remove</a>" +
		"<input type='hidden' id='a_id_"+q_id+"' value='0'/><div id='answers_"+q_id+"'/>" +
		"<h3 class='create nofloat'><a href='#' onClick='addPollAnswer("+q_id+"); return false;'>+ Add suggested answer</a></h3>" +
		"</div>");
	$("#question"+q_id).animate({opacity:1}, 500);
  document.getElementById("q_id").value = q_id+1;
}

function removePollQuestion(q_id) {
	$("#question"+q_id).animate({opacity:0}, 500, "", function() { $("#question"+q_id).remove(); } );
}

function addPollAnswer(q_id) {
	var a_id = Number(document.getElementById("a_id_"+q_id).value);
	$("#answers_"+q_id).append("<div id='answer_"+q_id+"_"+a_id+"'><h4>Suggested Answer</h4>" +
	"<textarea name='Answers["+q_id+"]["+a_id+"]' id='answer_text_"+q_id+"_"+a_id+"' cols='30' rows='1'></textarea>" +
	"<br/><a href='#' onClick='removePollAnswer("+q_id+","+a_id+"); return false;'>remove</a>" +
	"</div>"
	);
	document.getElementById("a_id_"+q_id).value = a_id+1;
}

function removePollAnswer(q_id,a_id) {
	$("#answer_"+q_id+"_"+a_id).animate({opacity:0}, 500, "", function() { $("#answer_"+q_id+"_"+a_id).remove(); } );
}



/* SMSnets carousel */
var current = 1;
function mycarousel_initCallback(carousel) {
	$('a.content_carousel').bind('click', function() {
		carousel.scroll($.jcarousel.intval($(this).attr('rel')));
		$(this).parent().siblings().removeClass('active');
		$(this).parent().addClass('active');
		current = parseInt( $(this).attr('rel') );
		return false;
	});
	
	$('.mycarousel-nav .next').bind('click', function() {
        carousel.next();
		var i = 0;
		current++;
		$('#carousel_controls li').each( function() {
			i++;
			if ( current == i  ) $(this).addClass('active');
			else $(this).removeClass('active');
		});
        return false;
    });

    $('.mycarousel-nav .prev').bind('click', function() {
        carousel.prev();
		var i = 0;
		current--;
		$('#carousel_controls li').each( function() {
			i++;
			if ( current == i  ) $(this).addClass('active');
			else $(this).removeClass('active');
		});
        return false;
    });
}

/* character counter */
// creates a counter for all fields with "counter='arg1'" on them
// if you pass in, say, multiple text areas, a counter for each individual textarea
// plus an optional counter for the total, can be incremented

// ASSUMPTIONS:
// - textarea or input field being counted has a unique name, like "fieldName"
// - counter for each individual field has an ID like "counter_fieldName"
// 		> this counter element has a <span class="count">0</span> with the integer to be incremented
// - multiple counters that you want totaled are group by the "counter" argument, like
//  	<input name="field1" counter="fieldGroup" />
//  	<input name="field2" counter="fieldGroup" />
//  	<input name="field3" counter="fieldGroup" />
// - counter for total then has an ID "fieldGroup_msg"

$.fn.counter = function( message_max, total ) {

  $(this).each(function() {
	var group = $(this).attr('counter');
    // var message_max = 155;
    var this_val = $(this).attr('value').length;
    var this_name = $(this).attr('name');
	var total_cur = 0;
	
    // value="", or no value at all will cause an error
	if ( !this_val ) this_val = 0;
	$('#counter_'+this_name+' span.count').text( this_val.toString() );

	$('*[counter="'+group+'"]').each( function() { 
    	total_cur += $(this).attr('value').length; 
	});
	$('#'+group+'_msg .total_chars').text( total_cur.toString() );
	if ( $("input[name='max_"+group+"']").length == 0 ) $('#'+group+'_msg .total_chars').after( "<input type='hidden' required='group_length' class='check valid' max='"+message_max+"' name='max_"+group+"' />" );

	if ( total_cur > message_max ) {
		$('#'+group+'_msg').addClass('error');
	}
	else {
		$('#'+group+'_msg').removeClass('error');
	}
	if ( this_val > message_max ) {
		$('#counter_'+this_name).addClass('error');
	}
	else {
		$('#counter_'+this_name).removeClass('error');
	}
	
	// do it all again, on keyup.
	// should abstract this since it's repeat code from right above.
    $(this).keyup(function(i) {		
	    var this_val = $(this).attr('value').length;
	    var this_name = $(this).attr('name');
		var total_cur = 0;

	    // value="", or no value at all will cause an error
		if ( !this_val ) this_val = 0;
		$('#counter_'+this_name+' span.count').text( this_val.toString() );
		$('*[counter="'+group+'"]').each( function() { 
	    	total_cur += $(this).attr('value').length; 
		});
		$('#'+group+'_msg .total_chars').text( total_cur.toString() );

		if ( total_cur > message_max ) {
			$('#'+group+'_msg').addClass('error');
		}
		else {
			$('#'+group+'_msg').removeClass('error');
		}
		if ( this_val > message_max ) {
			$('#counter_'+this_name).addClass('error');
		}
		else {
			$('#counter_'+this_name).removeClass('error');
		}


      return this;
    });
  });
  return this;
 }


/*** AJAX calls ***/
function resetPassword( UserID ) {
	$.ajax({
	  url: "/user/reset_password/" + UserID + "/ajax",
	  cache: false,
	  success: function(html){
		$('h1').after( html );
	  }
	});
}

function enableDisableCampaign( which, CampaignID, acctID ) {
	showLoader();
	$.ajax({
	  url: "/campaign/" + which + "/" + CampaignID + "/ajax",
	  cache: false,
	  success: function(html){
		var msg_html = html;
		$.ajax({
		  url: "/campaign/view/"+acctID+"/ajax",
		  cache: false,
		  success: function(html){
			hideLoader();
			$('#content').html(html);
			$('h1').after( msg_html );
		  }
		});
	  }
	});
}

// load the table of responses for a "poll" or "broadcast"  (type)
// function viewResponses( type, id ) {
// 	showLoader();
// 	$.ajax({
// 		// BRIAN: make the URL on this line the correct URL for pulling in poll/broadcast responses
// 	  // url: "/static/html_for_ajax/poll_responses.html/" + type + "/" + id + "/ajax",
// 	
// 		// for now, it's a hard-coded static URL
// 	  url: "/static/html_for_ajax/"+type+"_responses.html",
// 	  cache: false,
// 	  success: function(html){
// 		$('#'+type+'_'+id+'_responses').html( html );
// 		$('#'+type+'_'+id+'_responses').parent().parent().toggle(0);
// 		// $('#'+type+'_'+id+'_responses').slideDown();
// 		hideLoader();
// 	  }
// 	});
// }

function viewResponses( type, id ) {
	showLoader();
	$.ajax({
        url: "/action/view_"+type+"/"+id+"/ajax",
        cache: false,
        success: function(html){
			if ( $('#'+type+'_'+id ).length == 0 ) $('#'+id+' .'+type).append( html );
//		$('#'+id+' .sends').parent().parent().toggle(0);
		// $('#'+type+'_'+id+'_responses').slideDown();
		hideLoader();
	  }
	});
}

function addSubscriber(type, id, acct_id) {
	showLoader();
	
	if (type=="create") type = "add";
	
	$.ajax({
	  url: "/subscriber/"+type+"/"+id+"/ajax",
	  type: "POST",
	  cache: false,
	  data: { CellNumber:$('input[name=CellNumber]').val(), FirstName:$('input[name=FirstName]').val(), LastName:$('input[name=LastName]').val(), ZipCode:$('input[name=ZipCode]').val() },
	  success: function(html){
		hideLoader();
		$('.form_container').html(html);
		// on success, request the subscriber list and inject into the dom
		$.ajax({
		  url: "/subscriber/view/"+acct_id+"/ajax",
		  cache: false,
		  success: function(html){
			hideLoader();
			$('#content').html(html);
		
		  }
		});
	  }
	});
}

/*** end AJAX calls ***/

// $("a.fancybox").fancybox({ 'overlayOpacity':0.5, 'frameWidth': 550 });
