$(document).ready(function(){
	var input = $('input.focus:first');
	if (input) {
		input.focus();
	}
});

$(document).ready(function() {
  $('a[class*=lightwindow]').facebox();
});

$(document).ready(function(){
	var inactive = false;
	$('div.accordion:first').each(function(){
		if($(this).hasClass("inactive")){
			inactive = true;
		}
	});
	if(!inactive){
		$('div.accordion').accordion({autoHeight: false});
	}
});

$(document).ready(
	function createSortableQuestions() {
		if($("#questions_list")) {
			$("#questions_list").sortable({update: updateSortableQuestions});
		}
	}	
);

$(document).ready(function(){
   	$("#scriptabs").parent("div").tabs({ cookie: { expires: 7 } });
	$("#scriptabs.rotate").each(function(s){
		$(this).parent("div").tabs("rotate", 7000);
	});
});

$(document).ready(function(){
	$("#repeating_slideshow").carousel({rotate: 5000});
});

$.fn.user_autocomplete = function () {
	
	return this.each(function() {
		var hiddenInput = "#" + this.id.substring(0, this.id.length - "_name".length) + "_id";
		var query = this;
		var queryId = this.id;
		var parameters = {};
		
		$(this).autocomplete("/user_searches", {
			extraParams: parameters,
			matchContains: true,
			selectFirst: true,
			minChars: 0,
			method: "POST",
			update: function(value,data) {
				if (document.userSelected) {
					document.userSelected(data[1], value);
				} else {
					$(hiddenInput).val(data[1]);
				}
			}
		});
		
	});
	
};

$(document).ready(function(){
	$("input.user_autocomplete").user_autocomplete();
});

function appendAffiliationSearchResult(queryId, returnedData) {
	var ul = $("#" + queryId + "_results");
	if (!ul) { return; }
	
	if(ul.hasClass("multiple")){
		ul.append(returnedData);
	}else{
		ul.html(returnedData);
	}
}

$.fn.affiliation_autocomplete = function(){
	
	return this.each(function() {  
		var query = this;
		var queryId = this.id;
		var parameters = {};
		if ($(this).hasClass("stateworklocation")) {
		  	parameters["categoryFilter"] = "worksite";
	    } else if ($(this).hasClass("worksite")) {
	 		parameters["categoryFilter"] = "worksite";
	    }
	
		if ($(this).hasClass("search_all")) {
			parameters["search_all"] = "yes";
		}
	
		$(this).autocomplete("/affiliation_searches", {
			extraParams: parameters,
			matchContains: true,
			selectFirst: true,
			minChars: 0,
			method: "POST",
			update: function(value,data){
				var showParameters = {};
				var regex = /fieldName=(\S+)/;
				var match = regex.exec($(query).attr("class"));
				if(match){
					showParameters["field_name"] = match[1];
				}
				var id = data[1];
				var ul = $("#" + queryId + "_results");
				if (!ul) { alert("UL must be present"); return; }
				$.get("/affiliation_searches/" + id, 
					showParameters,
					function(returnedData){
						if (document.affiliation_autocomplete_insert_callback) {
							document.affiliation_autocomplete_insert_callback(query, id);
						}
						appendAffiliationSearchResult(queryId, returnedData);
					}
				);
			}
		});
	});
};

$(document).ready(function(){
	$("input.affiliation_autocomplete").affiliation_autocomplete();
});

function removeAffiliationAutocomplete(id) {
	$('#' + id).remove();
	if (document.affiliation_autocomplete_remove_callback) {
		document.affiliation_autocomplete_remove_callback(id);
	}
}

function updateSortableQuestions(event,ui){
	var position = 1;
	$("#questions_list input.position").each(
		function(i) {
			this.value = position++;
 		}
	);
}

function resetField(field, reset) {
  var vd = field.defaultValue;
  if (field.value == (reset ? '' : vd)) {
		field.value = (reset ? vd : '' );
  }
}

function remove_row_parent_of_td(element) {
    $(element).prev("tr").remove();
}

function getCookie( cookie_name ) {
	var start = document.cookie.indexOf( cookie_name + "=" );
	var len = start + cookie_name.length + 1;
	if ( ( !start ) && ( cookie_name != document.cookie.substring( 0, cookie_name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name_for_cookie, value_for_cookie, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name_for_cookie+'='+escape( value_for_cookie ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function deleteCampaignQuestion(el) {
	$(el).parents('li.action_campaign_question').remove();
}

function addedCampaignQuestion() {
	$('#questions_list .action_campaign_question:last').slideDown("slow");
	updateSortableQuestions();
}

$(document).ready(function(){
	$(".question_required_checkbox").each(function(checkbox){
		updateQuestionRequiredField(this);
	});
});

function updateQuestionRequiredField(checkbox) {
	if (checkbox.checked) {
		$(checkbox).next().disabled = true;
	} else {
		$(checkbox).next().disabled = false;
	}
}

function searchUsingZip(id, uri, el, value, campaign_id) {
	if (value.length == 5) {
		$('#zip_spinner').show();
		$.get(uri, { text: value, campaign_id: campaign_id }, function(data, textStatus) {
			$(id).html(data);
			$('#zip_spinner').hide(); 
		});
	} else {
		$(id).html("");
	}
}

function searchElectedOfficials(uri, el, value, campaign_id) {
	searchUsingZip('#elected_officials', uri, el, value, campaign_id);
}

function searchMediaOutlets(uri, el, value, campaign_id) {
	searchUsingZip('#media_outlets', uri, el, value, campaign_id);
}

function insertDependentAffiliationCategory(object, value) {
	$('.hidden_affiliation_' + value).show();
}

function removeDependentAffiliationCategory(value) {
	$('.hidden_affiliation_' + value).hide();
}

function initDepedendentAffiliations() {

	document.affiliation_autocomplete_insert_callback = function(element, value) {
		insertDependentAffiliationCategory(element, value);
	};

	document.affiliation_autocomplete_remove_callback = function(val) {
		removeDependentAffiliationCategory(val);
	};

	$('input[name="user[affiliation_ids][]"]').click(function() {
		if ($(this).is(":checked")) {
			insertDependentAffiliationCategory(this, this.value);
		} else {
			removeDependentAffiliationCategory(this.value);
		}
	});

	$('select[name="user[affiliation_ids][]"]').change(function() {
		var select = this;
		
		$(this).find("option").each(function() {
			removeDependentAffiliationCategory(this.value);
		});
		
		insertDependentAffiliationCategory(this, this.value);
	});
}

function next_tour(current, next) {
	if (current != null) { 
		$(current).hide();
	}
	if (next != null) {
		$(next).show();
	}
}